MicroOrm adapter for JsonApi Plugin for NestJs
npm install @klerick/json-api-nestjs-microormMocroOrm adapter for json-api-nestjs
``bash`
$ npm install @klerick/json-api-nestjs-microorm
The following interface is using for the configuration:
`typescript`
export type MicroOrmParam = {
arrayType?: string[]; //Custom type for indicate of array
};
@mikro-orm/nestjs does not create a default named context.
As a result, the module initialization behaves differently depending on whether a single or multiple connections are used.
More specifically, the dependency injection token for MikroORM differs between one and multiple database connections.
To maintain a consistent JSON:API module configuration across different database adapters,
I decided not to add extra conditional checks in the setup.
For everything to work correctly, @mikro-orm/nestjs should be integrated using the following module:
š MicroORM Database Module.
`typescript
import ormConfig from './config';
// need set contextName and registerRequestContext
export const config: Options = {
contextName: 'default',
registerRequestContext: false,
...ormConfig,
};
@Module({
imports: [MikroOrmModule.forRoot(config), MikroOrmModule.forMiddleware()],
exports: [MikroOrmCoreModule],
})
export class MicroOrmDatabaseModule {}
`
To enable automatic resource linkage (data field in relationships) for to-one relations, add a virtual FK field with persist: false.
Important: The FK field name must follow the pattern: {relationName} + Id (e.g., relation createdBy ā FK field createdById).
Example:
`typescript
import {
Entity,
PrimaryKey,
Property,
ManyToOne,
Ref,
Opt,
} from '@mikro-orm/core';
@Entity({ tableName: 'comments' })
export class Comments {
@PrimaryKey()
public id!: number;
@ManyToOne(() => Users)
public user!: Ref
// Virtual FK field for resource linkage
// Must have persist: false and name pattern: {relation}Id
@Property({ persist: false })
public userId!: number & Opt;
}
`
The library automatically detects FK fields based on:
1. The naming convention ({relationName}Id)persist: false
2. The option (marks it as a virtual/computed field)
This FK value will be used to populate relationships.{relation}.data` in API responses.