Appearance
IdModule
The IdModule
provides a simple and reliable way to generate unique identifiers for entities and data objects in your application.
What ID format used for entities
Each entity in the database has a specific ID format that consists of three parts:
plaintext
{product_shortname}{entity_id_prefix}{:env}?:{generated_string:11}
For example: libb:jgk28tyunfl or libb:dev:jgk28tyunfl on development server
Product Shortname: This represents the short name of the product (e.g., lib
).
Entity ID Prefix: This is a single character prefix that indicates the entity type (e.g., b
for Book).
Env: The env component in the ID format represents the environment in which the application is running, such as dev
or stage
. By including the environment identifier in the ID, it ensures traceability and helps differentiate entities across various environments. For instance, a development server would have an ID like libb:dev:jgk28tyunfl
. The env
component in the ID format is only added for dev
or stage
environments
Generated String: An 11-character unique string generated using the URL-safe alphabet (e.g., jgk28tyunfl
).
In the example provided, libb:jgk28tyunfl
, lib
is the product shortname, b
is the entity ID prefix, dev
is env component and jgk28tyunfl
is the generated string.
How to install the IdModule in your application
To install the IdModule
in your application, you'll need to follow these steps:
Install the required dependencies for
IdModule
:Import the
IdModule
from the@deeepvision/nest-kit
package.tsimport { IdModule } from '@deeepvision/nest-kit/dist/modules/id';
Next, add the
IdModule
to the imports array within the@Module
decorator of yourAppModule
. This will make the functionality of theIdModule
available throughout your application.ts@Module({ imports: [ IdModule, // ... other modules ], // ... other configurations }) export class AppModule {}
By adding the
IdModule
to yourAppModule
, you can now leverage its features to generate unique IDs for your entities, following the specific ID format mentioned earlier.
Create IdPrefix
enum
The IdPrefix
enum provides a set of predefined ID prefixes that can be used to uniquely identify different types of entities in an application.
ts
// /enums/id-prefix.ts
export enum IdPrefix {
BOOK = 'b',
ORGANIZATION = 'org'
...
}
Inject and use IdService
You can inject globally provided IdService to your service and call generateEntityId method
ts
import { IdService } from '@deeepvision/nest-kit/dist/modules/id';
import { IdPrefix } from '@/enums/id-prefix';
@Injectable()
export class BooksService {
constructor(
...
private readonly idService: IdService,
) {
}
async create(opts: CreateBookOptions, ctx: ServiceMethodContext): Promise<Book> {
const logger = this.logger.forMethod('create', ctx);
const book = this.bookRepository.create({
id: this.idService.generateEntityId(IdPrefix.BOOK), // libb:j39t85lgutk
...opts,
});
}
...
}