@sodacore/prisma
The Prisma plugin for the Sodacore framework provides a simplistic integration with the Prisma ORM and allows you to easily use Prisma within your Sodacore application.
Installation
To install the plugin, simply install it via bun:
bun install @sodacore/prisma prisma @prisma/client
And within your main.ts
file you can use the plugin like so:
import { Application } from '@sodacore/core';
import PrismaPlugin from '@sodacore/prisma';
const app = new Application({
autowire: true,
});
app.use(new PrismaPlugin());
app.start().catch(console.error);
You would need to follow the normal Prisma setup process to create your schema file, generate the client, and run migrations, as per the Prisma documentation.
This plugin simply aims to try and simplify the integration process and make it easier to use Prisma within your Sodacore application.
Extending Prisma
You can add plugins and extend the Prisma functionality by adding an onInit
method within the configuration:
app.use(new PrismaPlugin({
onInit: (prisma) => {
// Extend the Prisma client here.
},
}));
Configuration
The Prisma plugin accepts the following configuration options:
export type IConfig = {
schemaFileLocation?: string, // Only use if the automatic resolver fails.
onInit?: (prisma: any) => void | Promise<void>,
};
The schema file location can define where to load the Prisma client from, we automatically read it from the prisma
directory, but if you have a custom setup you can define it here, which we shall then use to lookup the prisma client to inject.
Usage
By default the Prisma client is dynamically imported from the path defined within the schema file, the service is then registered to initialise the Prisma client and make it available for injection.
CAUTION
In the recent versions of Prisma the generated client is a compiled class with no fixed name, therefore importing it nicely is not possible, as the class name is dynamic and can sometimes be a single letter, so going forward, you must inject the Prisma client using the prisma
string, like so:
import type { PrismaClient } from '../your-prisma-path'; // Adjust the import path accordingly.
import { Controller, Get } from '@sodacore/core';
import { Inject } from '@sodacore/di';
@Controller('/users')
export class UserController {
@Inject('prisma') private prisma!: PrismaClient;
@Get('/')
public async getUsers() {
return this.prisma.user.findMany();
}
}