PrismaP
Prisma13mo ago
15 replies
TutoDS

Nestjs Prisma extension

Hi everyone
I'm trying to fill the code field with a custom nanoid() with only uppercase letters and numbers, but when I do the $extends with my logic, I have two problems:
- I think my custom nanoid() isn't working
- Typescript is complaining because I didn't fill the code on the .create

This is my prisma service:
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
  private readonly logger = new Logger(PrismaService.name);
  #nanoid: (size?: number) => string = undefined;

  constructor() {
    super();
    this.#nanoid = customAlphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 4);
  }

  async onModuleInit() {
    this.logger.log(`CODE: ${this.#nanoid()}`);

    this.$extends({
      model: {
        customer: {
          create: ({ args, query }) => {
            args.data = {
              ...args.data,
              code: this.#nanoid(),
            };

            query(args);
          },
        },
      },
    }).$extends(
      createSoftDeleteExtension({
        models: {
          User: true,
          Customer: true,
        },
        defaultConfig: {
          field: 'deletedAt',
          createValue: (deleted) => {
            if (deleted) {
              return new Date();
            }
            return null;
          },
        },
      }),
    );

    await this.$connect();
  }

  async onModuleDestroy() {
    await this.$disconnect();
  }
}
Was this page helpful?