0.0.16 • Published 5 months ago
@gnx-utilities/services v0.0.16
📝 Generics Services
Generic services is a library that allows you to create services with a generic repository, this library is based on the Sequelizer library and also in Typegoose.
📦 Installation
npm install @services/generic-services
pnpm install @services/generic-services
yarn add @services/generic-services
bun install @services/generic-services
📖 Usage
Sequelize
import { Sequelize } from 'sequelize';
import { SequelizeService } from '@services/@services/generic-services';
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: ':memory:',
});
class User extends Sequelize.Model {}
User.init(
{
firstName: Sequelize.STRING,
lastName: Sequelize.STRING,
},
{ sequelize, modelName: 'user' },
);
const userService = new SequelizeService(User);
const user = await userService.create({ firstName: 'John', lastName: 'Doe' });
console.log(user.firstName); // John
Typegoose
import { TypegooseService } from '@services/generic-services';
import { prop, getModelForClass } from '@typegoose/typegoose';
class User {
@prop()
firstName: string;
@prop()
lastName: string;
}
const UserModel = getModelForClass(User);
const userService = new TypegooseService(UserModel);
const user = await userService.create({ firstName: 'John', lastName: 'Doe' });
console.log(user.firstName); // John
Override methods
import { SequelizeService } from '@services/generic-services';
import { ServiceParams, ServiceParamsWithEntity, ServiceParamsWithId } from '@services/generic-services/models/types';
export class UserService extends SequelizeService {
constructor() {
super(User);
}
override async create({ entity }: ServiceParamsWithEntity<User>) {
// your code here
return super.create({ entity });
}
override async update({ id, entity }: ServiceParams) {
// your code here
return super.update({ id, entity });
}
override async delete({ id }: ServiceParamsWithId) {
// your code here
return super.delete({ id });
}
}
import { TypegooseService } from '@services/generic-services';
import { ServiceParams, ServiceParamsWithEntity, ServiceParamsWithId } from '@services/generic-services/models/types';
export class UserService extends TypegooseService {
constructor() {
super(User);
}
override async create({ entity }: ServiceParamsWithEntity<User>) {
// your code here
return super.create({ entity });
}
override async update({ id, entity }: ServiceParams) {
// your code here
return super.update({ id, entity });
}
override async delete({ id }: ServiceParamsWithId) {
// your code here
return super.delete({ id });
}
}
📚 Documentation
Methods
Method | Description |
---|---|
create({ entity }) | Create a new entity and return it |
getAll() | Get all entities |
getById({ id }) | Get an entity by id |
update({ id, entity }) | Update an entity by id |
delete({ id }) | Delete an entity by id |