Here’s a comprehensive documentation for your nest-typeorm-factory
package, highlighting installation, usage, and case scenarios for all API features.
nest-typeorm-factory
is a utility package designed to streamline CRUD operations and advanced filtering in NestJS applications that use TypeORM. This package provides convenient handler functions for retrieving, creating, updating, and deleting records, with support for filtering, pagination, sorting, field selection and populating inter-table relationships.
To use nest-typeorm-factory
in your NestJS project, install it via npm:
npm install nest-typeorm-factory
Ensure you have TypeORM set up in your project, as it’s required for the package to function with your repositories.
Import the package and utilize it within your NestJS service to handle common database operations.
Let's create 2 entities, one for Post
, the other for User
The User
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from 'typeorm';
import { Post } from './post.entity';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
email: string;
@OneToMany(() => Post, post => post.user)
posts: Post[];
}
The Post
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from 'typeorm';
import { User } from './user.entity';
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column()
content: string;
@Column()
category: string;
@Column({ default:0 })
reposts: number;
@Column({ default: () => 'CURRENT_TIMESTAMP' })
createdAt: Date;
@ManyToOne(() => User, user => user.posts)
user: User;
}
⚠️ Warning:
When creating your entities be sure to addcreatedAt
field.
import { Repository } from "typeorm"
import { Injectable } from "@nestjs/common"
import { InjectRepository } from "@nestjs/typeorm"
//DTOs
import { CreatePostDto } from "./dto/create-post.dto"
import { UpdatePostDto } from "./dto/update-post.dto"
//Entities
import { Post } from "./entities/post.entity"
//Package
import { factory, IQuery } from "nest-typeorm-factory"
@Injectable()
export class PostService {
constructor(
@InjectRepository(Post) private postRepository: Repository<Post>
) {}
// CRUD operations implemented using factory functions from nest-typeorm-factory
}
Use the createOne
function to create a new record. This method takes a repository instance and the data to create as arguments.
async create(createPostDto: CreatePostDto) {
return await factory.createOne(this.postRepository, createPostDto);
}
Retrieve a list of records with advanced query options by using getAll
.
async findAll(query: IQuery) {
return await factory.getAll(this.postRepository, query);
}
Use getOne
to retrieve a single record by its ID.
async findOne(id: string, query: IQuery) {
return await factory.getOne(this.postRepository, id, query);
}
Use updateOne
to update an existing record by its ID.
async update(id: string, updatePostDto: UpdatePostDto) {
return await factory.updateOne(this.postRepository, id, updatePostDto);
}
Use deleteOne
to delete a record by its ID.
async remove(id: string) {
return await factory.deleteOne(this.postRepository, id);
}
Making use of the package, this is what your controller will look like.
import {
Get,
Post,
Body,
Query,
Patch,
Param,
Delete,
Controller,
} from '@nestjs/common';
import { PostService } from './post.service';
import { CreatePostDto } from './dto/create-post.dto';
import { UpdatePostDto } from './dto/update-post.dto';
import { IQuery } from 'nest-typeorm-factory';
@Controller('posts')
export class PostController {
constructor(private readonly postService: PostService) {}
@Post()
async create(@Body() createPostDto: CreatePostDto) {
return this.postService.create(createPostDto);
}
@Get()
async findAll(@Query() query: IQuery) {
return this.postService.findAll(query);
}
@Get(':id')
async findOne(@Param('id') id: string, @Query() query: IQuery) {
return this.postService.findOne(id, query);
}
@Patch(':id')
async update(@Param('id') id: string, @Body() updatePostDto: UpdatePostDto) {
return this.postService.update(id, updatePostDto);
}
@Delete(':id')
async remove(@Param('id') id: string) {
return this.postService.remove(id);
}
}
Each function supports a set of advanced query options, which include filtering, sorting, pagination, and more.
Filter results based on fields that are an exact match.
GET /posts?category=fashion
Filter results with advanced options like greater than, less than, greater than or equals, less than or equals.
GET /posts?gt=reposts,50
GET /posts?gte=reposts,50
GET /posts?lt=reposts,50
GET /posts?lte=reposts,50
You can also apply the OR
logic while filtering e.g you want to match all posts with a title of either sports
, fashion
, or tech
.
Here's how you can do that.
GET /posts?category=sports,fashion,tech
Sort records using asc-fieldName
or desc-fieldName
.
GET /posts?sort=asc-title
OR
GET /posts?sort=desc-createdAt
⚠️ Note:
If no sort parameter is passed in, it will sort by thecreatedAt
property in descending order by default.
Limit the fields returned by specifying fields
.
GET /posts?fields=title,createdAt
Control pagination with page
and limit
.
GET /posts?page=2&limit=5
Use the search
parameter to match keywords like so.
GET /posts?search=fieldA,searchTermA
GET /posts?search=title,JavaScri
You can also search against multiple fields.
GET /posts?search=fieldA,searchTermA-fieldB,searchTermB
GET /posts?search=title,JavaScri-content,variables
Retrieve records that have the value of a particular field within a range.
GET /posts?range=reposts,5-50
Populate Inter Table relationships while querying records. This works for all kinds of relationships, i.e One-To-One
, Many-To-One
, One-To-Many
and Many-To-Many
GET /posts?relations=user
Supposing our entity has multiple relationships with other tables. This is how we'll do it
GET /posts?relations=user,fieldB,fieldC
The same also works for getting a resource by id
GET /posts/{id}?relations=user
GET /posts/{id}?relations=user,fieldB,fieldC
You can combine multiple API features together like so
GET /posts?title=JavaScri&reposts=5&relations=user&page=2&sort=desc-createdAt
The package provides consistent error handling with descriptive messages for missing records, invalid parameters, and other common issues.
- 404 Not Found - Record does not exist.
- 400 Bad Request - Invalid parameters provided.
POST /posts
Content-Type: application/json
{
"title": "My NestJS Post",
"content": "Exploring the nest-typeorm-factory package."
"userId": "67890"
}
{
"status": "success",
"data": {
"id": "12345",
"title": "My NestJS Post",
"content": "Exploring the nest-typeorm-factory package."
"user": {
"id": "67890",
"name": "John Doe",
"email": "johndoe@example.com"
}
}
}
GET /posts?sort=asc-title&page=1&limit=10&search=title,NestJS
{
"status": "success",
"data": [
{
"id": "12345",
"title": "My NestJS Post",
"createdAt": "2023-11-01T10:00:00Z"
}
]
}
PATCH /posts/12345
Content-Type: application/json
{
"title": "Updated NestJS Post Title"
}
{
"status": "success",
"data": {
"id": "12345",
"title": "Updated NestJS Post Title",
"updatedAt": "2023-11-01T10:30:00Z"
}
}
DELETE /posts/12345
{
"status": "success",
"message": "Post deleted successfully"
}
nest-typeorm-factory
is open-source software licensed under the MIT License.
For issues or contributions, visit GitHub Repository.