PrismaService
This file defines the PrismaService
class, which manages the lifecycle and configuration of the Prisma client within the @sodacore/core
framework. It handles dynamic loading of the Prisma client, initialization, connection, disconnection, and registration of the client in the Sodacore registry for global access and dependency injection.
Features
- Dynamic Prisma Client Loading: Parses the Prisma schema to determine the correct client output path and dynamically imports the Prisma client.
- Lifecycle Management: Handles initialization (
init
), connection (start
), and disconnection (stop
) of the Prisma client. - Registry Integration: Registers the Prisma client instance in the Sodacore registry for global and DI-based access.
- Custom Initialization Hook: Supports an optional
onInit
callback in the config for custom Prisma setup logic. - Schema File Resolution: Resolves the Prisma schema file path, supporting custom output paths if specified.
Usage
typescript
import PrismaService from './service/prisma';
const prismaService = new PrismaService();
await prismaService.init();
await prismaService.start();
// ... use Prisma client via registry or dependency injection
await prismaService.stop();
API
Properties
- config: Optional Prisma configuration, injected via DI. May include an
onInit
callback and custom client path. - prisma: The Prisma client instance, initialized during
init
.
Methods
async init(): Promise<void>
- Loads and parses the Prisma schema file.
- Determines the correct Prisma client output path.
- Dynamically imports the Prisma client.
- Instantiates and registers the Prisma client in the registry.
- Calls the optional
onInit
hook from the config.
async start(): Promise<void>
- Connects the Prisma client to the database.
async stop(): Promise<void>
- Disconnects the Prisma client from the database.
private async getSchemaFile(): Promise<File>
- Resolves and returns the Prisma schema file handle.
- Throws an error if the schema file is not found.
How It Works
Initialization:
- Loads the Prisma schema and parses it to find the client output path.
- Dynamically imports the Prisma client from the resolved path.
- Instantiates the client and registers it in the Sodacore registry.
- Executes any custom initialization logic provided in the config.
Start/Stop:
start()
connects the Prisma client to the database.stop()
disconnects the Prisma client from the database.
Schema File Handling:
- Uses the configured
generatedClientPath
if provided, otherwise defaults to./prisma/schema.prisma
.
- Uses the configured
Notes
- Throws an error if the Prisma client or schema file cannot be found.
- Designed to be used as a service within the