@klerick/json-api-nestjs
v10.0.0-beta.18
Published
JsonApi Plugin for NestJs
Maintainers
Readme
json-api-nestjs
This plugin works upon TypeOrm or MicroOrm library, which is used as the main database abstraction layer tool. The module automatically generates an API according to JSON API specification from the database structure (TypeOrm or MicroOrm entities). It supports features such as requests validation based on database fields types, request filtering, endpoints extending, data relations control and much more. Our module significantly reduces the development time of REST services by removing the need to negotiate the mechanism of client-server interaction and implementing automatic API generation without the need to write any code.
Installation
$ npm install @klerick/json-api-nestjsExample
Once the installation process is complete, we can import the JsonApiModule into the root AppModule.
TypeOrm
import {Module} from '@nestjs/common';
import {JsonApiModule} from '@klerick/json-api-nestjs';
import {TypeOrmJsonApiModule} from '@klerick/json-api-nestjs-typeorm';
import {Users} from 'type-orm/database';
@Module({
imports: [
JsonApiModule.forRoot(TypeOrmJsonApiModule, {
entities: [Users]
}),
],
})
export class AppModule {
}MicroOrm
import {Module} from '@nestjs/common';
import {JsonApiModule} from '@klerick/json-api-nestjs';
import {MicroOrmJsonApiModule} from '@klerick/json-api-nestjs-microorm';
import {Users} from 'micro-orm/database';
@Module({
imports: [
JsonApiModule.forRoot(MicroOrmJsonApiModule, {
entities: [Users]
}),
],
})
export class AppModule {
}After this, you have to prepare CRUDs with ready-to-use endpoints:
- GET /users
- POST /users
- GET /users/:id
- PATCH /users/:id
- DELETE /users/:id
- GET /users/{id}/relationships/{relName}
- POST /users/{id}/relationships/{relName}
- PATCH /users/{id}/relationships/{relName}
- DELETE /users/{id}/relationships/{relName}
Configuration params
The following interface is using for the configuration:
export interface ModuleOptions {
entities: Entity[]; // List of typeOrm Entity
excludeControllers?: Entity[]; // List of entities to exclude from automatic controller generation
controllers?: NestController[]; // List of controller, if you need extend default present
connectionName?: string; // Type orm connection name: "default" is default name
providers?: NestProvider[]; // List of addition provider for useing in custom controller
imports?: NestImport[]; // List of addition module for useing in custom controller
options?: {
requiredSelectField?: boolean; // Need list of select field in get endpoint, try is default
debug?: boolean; // Debug info in result object, like error message
pipeForId?: Type<PipeTransform> // Nestjs pipe for validate id params, by default ParseIntPipe
operationUrl?: string // Url for atomic operation https://jsonapi.org/ext/atomic/
allowSetId?: boolean // Allow client to set id on POST requests, false by default
// You can add params for MicroOrm or TypeOrm adapter
} ;
}Excluding Controllers
If you need to register entities for relationships but don't want automatic controller generation for some of them, use excludeControllers:
import {Module} from '@nestjs/common';
import {JsonApiModule} from '@klerick/json-api-nestjs';
import {TypeOrmJsonApiModule} from '@klerick/json-api-nestjs-typeorm';
import {Users, Roles, AuditLog} from 'database';
@Module({
imports: [
JsonApiModule.forRoot(TypeOrmJsonApiModule, {
entities: [Users, Roles, AuditLog],
excludeControllers: [AuditLog], // AuditLog entity will not have auto-generated controller
}),
],
})
export class AppModule {}This is useful when:
- You want to manage certain entities only through relationships
- You need custom controller implementation without the auto-generated one
- Some entities should be internal and not exposed via REST API
You can extend the default controller:
import {Get, Param, Inject, BadRequestException} from '@nestjs/common';
import {Users} from 'database';
import {
JsonApi,
excludeMethod,
JsonBaseController,
InjectService,
JsonApiService,
Query,
} from '@klerick/json-api-nestjs';
import {
ResourceObjectRelationships,
} from '@klerick/json-api-nestjs-shared';
import {ExampleService} from '../../service/example/example.service';
@JsonApi(Users, {
allowMethod: excludeMethod(['deleteRelationship']),
requiredSelectField: true,
overrideRoute: 'user',
})
export class ExtendUserController extends JsonBaseController<Users, 'id'> {
@InjectService() public service: JsonApiService<Users>;
@Inject(ExampleService) protected exampleService: ExampleService;
public override getAll(query: Query<Users, 'id'>): Promise<ResourceObject<Users, 'array'>> {
if (!this.exampleService.someCheck(query)) {
throw new BadRequestException({});
}
return this.service.getAll(query);// OR call parent method: super.getAll(query);
}
public override patchRelationship<Rel extends EntityRelation<Users>>(
id: string | number,
relName: Rel,
input: PatchRelationshipData
): Promise<ResourceObjectRelationships<Users, 'id', Rel>> {
return super.patchRelationship(id, relName, input);
}
@Get(':id/example')
testOne(@Param('id') id: string): string {
return this.exampleService.testMethode(id);
}
}You can overwrite the default config for the current controller using options in the decorator JsonAPi. Also you can specify an API method necessary for you, using allowMethod Defulat validation check only simple type and database structure. If you need custom pipe validation you can your owner pipe like this:
import { Query } from '@nestjs/common';
import {
JsonApi,
excludeMethod,
JsonBaseController,
InjectService,
JsonApiService,
Query as QueryType,
} from 'json-api-nestjs';
@JsonApi(Users, {
allowMethod: excludeMethod(['deleteRelationship']),
requiredSelectField: true,
overrideRoute: 'user',
})
export class ExtendUserController extends JsonBaseController<Users, 'id'> {
@InjectService() public service: JsonApiService<Users>;
@Inject(ExampleService) protected exampleService: ExampleService;
public override getAll(
@Query(ExamplePipe) query: QueryType<Users, 'id'>
): Promise<ResourceObject<Users, 'array'>> {
return super.getAll(query);
}
}import { ArgumentMetadata, PipeTransform } from '@nestjs/common';
import { Query } from 'json-api-nestjs';
import { Users } from 'database';
export class ExamplePipe implements PipeTransform<Query<Users, 'id'>, Query<Users, 'id'>> {
transform(value: Query<Users, 'id'>, metadata: ArgumentMetadata): Query<Users, 'id'> {
return value;
}
}Swagger UI
For using swagger, you should only add @nestjs/swagger and configure it
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setOpenAPIVersion('3.1.0')
.setTitle('JSON API swagger example')
.setDescription('The JSON API list example')
.setVersion('1.0')
.build();
SwaggerModule.setup(
'swagger',
app,
() => SwaggerModule.createDocument(app, config), // !!!Important: document as factory
{}
);
Available endpoint method
Using Users entity and relation Roles entity as example
List item of Users
GET /usersAvailable query params:
include - you can extend result with relations (aka join)
GET /users?include=rolesresult of request will have role relation for each Users item
fields - you can specify required fields of result query
GET /users?fields[target]=login,lastName&fileds[roles]=name,keyThe "target" is Users entity The "roles" is Roles entity So, result of request will be have only fields login and lastName for Users entity and fields name and * key* for Roles entity
sort - you can sort result of the request
GET /users?sort=target.name,-roles.keyThe "target" is Users entity The "roles" is Roles entity So, result of the request will be sorted by field name of Users by ASC and field key of Roles entity by DESC.
page - pagination for you request
GET /users?page[number]=1page[size]=20filter - filter for query
GET /users?filter[name][eq]=1&filter[roles.name][ne]=test&filter[roles.status][eq]=trueThe "name" is a field of Users entity The "roles.name" is name field of Roles entity The "eq", "ne" is Filter operand
So, this query will be transformed like sql:
WHERE users.name = 1 AND roles.name <> 'test' AND roles.status = true
Filter operand
type FilterOperand
{
in:string[] // is equal to the conditional of query "WHERE 'attribute_name' IN ('value1', 'value2')"
nin: string[] // is equal to the conditional of query "WHERE 'attribute_name' NOT IN ('value1', 'value1')"
eq: string // is equal to the conditional of query "WHERE 'attribute_name' = 'value1'
ne: string // is equal to the conditional of query "WHERE 'attribute_name' <> 'value1'
gte: string // is equal to the conditional of query "WHERE 'attribute_name' >= 'value1'
gt: string // is equal to the conditional of query "WHERE 'attribute_name' > 'value1'
lt: string // is equal to the conditional of query "WHERE 'attribute_name' < 'value1'
lte:string // is equal to the conditional of query "WHERE 'attribute_name' <= 'value1'
regexp: string // is equal to the conditional of query "WHERE 'attribute_name' ~* value1
some: string // is equal to the conditional of query "WHERE 'attribute_name' && [value1]
}Get item of Users
GET /users/:idinclude - you can extend result with relations (aka join)
GET /users?include=rolesresult of request will have role relation for each Users item
fields - you can specify required fields of result query
GET /users?fields[target]=login,lastName&fileds[roles]=name,keyThe "target" is Users entity The "roles" is Roles entity So, result of request will be have only fields login and lastName for Users entity and fields name and * key* for Roles entity
Create item of Users
POST /users- body - Create new User and add link to address
{
"data": {
"type": "users",
"attributes": {
"id": 0,
"login": "string",
"firstName": "string",
"lastName": "string",
"isActive": true,
"createdAt": "2023-12-08T10:32:27.352Z",
"updatedAt": "2023-12-08T10:32:27.352Z"
},
"relationships": {
"addresses": {
"id": "1",
"type": "addresses"
}
}
}
}Client-Generated IDs
By default, the server generates IDs for new resources. If you need clients to provide their own IDs (e.g., UUIDs), enable the allowSetId option:
@Module({
imports: [
JsonApiModule.forRoot(TypeOrmJsonApiModule, {
entities: [Users],
options: {
allowSetId: true,
},
}),
],
})
export class AppModule {}With this option enabled, clients can include the id field in POST requests:
{
"data": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"type": "users",
"attributes": {
"login": "johndoe",
"firstName": "John",
"lastName": "Doe"
}
}
}Note: When allowSetId is false (default), any id provided in the POST body will be ignored and the server will generate a new ID.
Update item of Users
PATCH /users/:id- body - Update User with id 1 and update link to address and manager
{
"data": {
"id": "1",
"type": "users",
"attributes": {
"id": 0,
"login": "string",
"firstName": "string",
"lastName": "string",
"isActive": true,
"createdAt": "2023-12-08T10:34:57.752Z",
"updatedAt": "2023-12-08T10:34:57.752Z"
},
"relationships": {
"addresses": {
"id": "2",
"type": "addresses"
},
"manager": {
"id": "2",
"type": "users"
}
}
}
}
Meta Support
The library supports the meta member in JSON:API requests and responses according to the JSON:API specification. Meta allows passing additional non-standard information that doesn't belong to resource attributes.
Use cases:
- Request tracking (correlation IDs, client versions, timestamps)
- Business logic metadata (import source, batch IDs, priority levels)
- Audit information (user context, operation reason)
Meta in Regular Operations
Meta is supported in POST, PATCH, and relationship operations:
POST Request with Meta:
POST /users
{
"data": {
"type": "users",
"attributes": {
"login": "johndoe",
"firstName": "John"
}
},
"meta": {
"source": "mobile-app",
"version": "1.0.2",
"correlationId": "abc-123"
}
}PATCH Request with Meta:
PATCH /users/1
{
"data": {
"id": "1",
"type": "users",
"attributes": {
"firstName": "Jane"
}
},
"meta": {
"reason": "name-change-request",
"approvedBy": "admin"
}
}Relationship Operations with Meta:
POST /users/1/relationships/roles
{
"data": [
{ "type": "roles", "id": "2" }
],
"meta": {
"assignedBy": "admin",
"expiresAt": "2024-12-31"
}
}Note: DELETE operations do not support meta as per JSON:API specification.
Accessing Meta in Controllers
Meta is automatically extracted and passed as a parameter to controller methods:
import { JsonApi, JsonBaseController } from '@klerick/json-api-nestjs';
import { Body } from '@nestjs/common';
@JsonApi(Users)
export class UsersController extends JsonBaseController<Users> {
override async postOne(
@Body() inputData: PostData<Users>,
@Body() meta: Record<string, unknown>
) {
// Access meta fields
console.log('Source:', meta.source);
console.log('Correlation ID:', meta.correlationId);
// Return response with meta
const response = await super.postOne(inputData);
return {
...response,
meta: {
...meta,
processedAt: Date.now(),
processedBy: 'server'
}
};
}
}Custom Meta Validation
You can add custom validation for meta using NestJS pipes:
import { PipeTransform, BadRequestException } from '@nestjs/common';
import { z } from 'zod';
// Define meta schema
const CustomMetaSchema = z.object({
source: z.string(),
version: z.string().regex(/^\d+\.\d+\.\d+$/),
correlationId: z.string().uuid().optional()
});
type CustomMeta = z.infer<typeof CustomMetaSchema>;
// Custom validation pipe
export class MetaValidationPipe implements PipeTransform<unknown, CustomMeta> {
transform(value: unknown): CustomMeta {
try {
return CustomMetaSchema.parse(value);
} catch (e) {
throw new BadRequestException('Invalid meta format');
}
}
}
// Use in controller
@JsonApi(Users)
export class UsersController extends JsonBaseController<Users> {
override async postOne(
@Body() inputData: PostData<Users>,
@Body(MetaValidationPipe) meta: CustomMeta
) {
// meta is now validated and typed
console.log(meta.version); // TypeScript knows this exists
return super.postOne(inputData);
}
}Atomic Operations
The library implements the JSON:API Atomic Operations Extension, allowing you to execute multiple operations in a single HTTP request with transaction support.
Use case: Create multiple related resources in one atomic request instead of multiple sequential HTTP requests.
Example: Create a new Role, create a new User, and assign the role to the user - all in one request instead of three separate requests.
Request Example:
{
"atomic:operations":[
{
"op":"add",
"ref":{
"type":"roles",
"lid":10000
},
"data":{
"type":"roles",
"attributes":{
"name":"admin",
"key":"admin_role"
}
}
},
{
"op":"add",
"ref":{
"type":"users"
},
"data":{
"type":"users",
"attributes":{
"login":"johndoe",
"firstName":"John",
"lastName":"Doe"
},
"relationships":{
"addresses":{
"data":{
"type":"addresses",
"id":"1"
}
},
"roles":{
"data":[
{
"type":"roles",
"id":"10000"
}
]
}
}
}
}
]
}Local Identifiers (lid):
- The
lid(local identifier) parameter allows referencing resources created within the same atomic request - Must be unique across all operations in the request
- Used in the
ref.lidfield for the operation creating the resource - Referenced in
relationships.{relation}.data.idto establish relationships - Automatically replaced with real database IDs by the server
Meta Support in Atomic Operations:
Each operation can include a meta object for additional metadata:
{
"atomic:operations": [
{
"op": "add",
"ref": { "type": "users", "lid": 1000 },
"data": {
"type": "users",
"attributes": { "login": "john" }
},
"meta": {
"source": "bulk-import",
"batchId": "batch-123",
"priority": "high"
}
},
{
"op": "update",
"ref": { "type": "users", "id": "5" },
"data": {
"type": "users",
"attributes": { "isActive": false }
},
"meta": {
"reason": "account-suspension",
"requestedBy": "admin"
}
}
]
}Meta is passed to controller methods just like in regular operations, allowing you to:
- Track operation context
- Apply business logic based on metadata
- Include metadata in response
Supported Operations:
add- Create a new resource (equivalent to POST)update- Update an existing resource (equivalent to PATCH)remove- Delete a resource (equivalent to DELETE)
Transaction Guarantees: All operations in an atomic request execute within a single database transaction:
- If all operations succeed → transaction commits
- If any operation fails → entire transaction rolls back (no partial changes)
Configuration:
JsonApiModule.forRoot(TypeOrmJsonApiModule, {
entities: [Users, Roles],
options: {
operationUrl: 'operation', // Default endpoint: POST /operation
allowSetId: true, // Allow clients to set IDs (useful for UUIDs)
}
})If you have Interceptor you can check call it from AtomicOperation
@Injectable()
export class AtomicInterceptor<T> implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler<T>): Observable<T> {
const isAtomic = context.getArgByIndex(3)
if (isAtomic) {
console.log('call from atomic operation')
}
return next.handle();
}
}isAtomic - is array of params of method
Resource Linkage for To-One Relations
According to the JSON:API specification, relationships should include a data member containing resource linkage (the id and type of the related resource).
For to-one relations (ManyToOne, OneToOne), if your entity has an FK field (foreign key), the library will automatically include relationships.{relation}.data in responses even without using include.
Example response:
{
"data": {
"id": "1",
"type": "comments",
"attributes": { "text": "Hello" },
"relationships": {
"user": {
"links": { "self": "/api/comments/1/relationships/user" },
"data": { "id": "5", "type": "users" }
}
}
}
}If the FK field is null, then data will also be null:
"relationships": {
"user": {
"links": { "self": "/api/comments/1/relationships/user" },
"data": null
}
}Note: TypeORM and MikroORM implement FK field detection differently. See the respective adapter documentation for details on how to define FK fields in your entities.
Field Access Control Decorators
The library provides two decorators to control field accessibility in POST and PATCH operations:
@JsonApiReadOnly()
Fields marked with @JsonApiReadOnly() are completely excluded from input validation schemas. They cannot be set via POST or PATCH requests and are not shown in Swagger documentation for input.
Use case: Server-managed fields like createdAt, updatedAt, computed fields.
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';
import { JsonApiReadOnly } from '@klerick/json-api-nestjs';
@Entity()
export class Users {
@PrimaryGeneratedColumn()
id: number;
@Column()
login: string;
@JsonApiReadOnly()
@CreateDateColumn()
createdAt: Date;
@JsonApiReadOnly()
@UpdateDateColumn()
updatedAt: Date;
}With this configuration:
- POST /users -
createdAtandupdatedAtfields are not accepted - PATCH /users/:id -
createdAtandupdatedAtfields are not accepted
@JsonApiImmutable()
Fields marked with @JsonApiImmutable() can be optionally set during creation (POST) but cannot be modified after (PATCH).
Use case: Fields that should be set once and never changed, like externalId, slug, or username.
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
import { JsonApiImmutable } from '@klerick/json-api-nestjs';
@Entity()
export class Users {
@PrimaryGeneratedColumn()
id: number;
@JsonApiImmutable()
@Column({ unique: true })
login: string;
@Column()
firstName: string;
@Column()
lastName: string;
}With this configuration:
- POST /users -
loginis optional, can be provided or omitted - PATCH /users/:id -
loginis not accepted (cannot be changed)
Combining Decorators
You can use both decorators in the same entity:
@Entity()
export class Article {
@PrimaryGeneratedColumn()
id: number;
@JsonApiImmutable()
@Column({ unique: true })
slug: string;
@Column()
title: string;
@Column()
content: string;
@JsonApiReadOnly()
@CreateDateColumn()
createdAt: Date;
@JsonApiReadOnly()
@UpdateDateColumn()
updatedAt: Date;
}| Field | POST | PATCH |
|-------|------|-------|
| slug | Optional | Not accepted |
| title | Required | Optional |
| content | Required | Optional |
| createdAt | Not accepted | Not accepted |
| updatedAt | Not accepted | Not accepted |
