sc-prisma-extractor
v1.0.3
Published
A CLI tool to extract your Prisma schema into usable TypeScript interfaces and a detailed metadata JSON file.
Maintainers
Readme
SC Prisma Extractor
A simple CLI tool to extract your Prisma schema into usable TypeScript interfaces and a detailed JSON metadata file. Helps bridge the gap between your database schema and application code, ensuring type safety.
Features
- Generates clean TypeScript
interfaceortypedefinitions from yourschema.prismafile. - Creates a
metadata.jsonfile with the complete DMMF (Data Model Meta Format) structure for advanced use cases. - Easy-to-use command-line interface with configurable output types.
Installation
For use in a project, install as a development dependency:
npm install sc-prisma-extractor --save-devOr, to use as a global system-wide tool:
npm install -g sc-prisma-extractorUsage
The extractor can be run with command-line arguments or with a configuration file.
npx sc-prisma-extractor [schema-path] [output-path] [options]Command Line Arguments & Options
schema-path: (Optional) Path to yourschema.prismafile.output-path: (Optional) Path for the generated TypeScript file.--init: Generates a defaultprisma-extractor.jsonconfiguration file.--config <path>: Specifies a custom path for the configuration file.--dry-run: Simulates the run without writing files to disk.
If schema-path and output-path are not provided, they must be specified in the configuration file.
Recommended Workflow
For a robust workflow, define paths and options in prisma-extractor.json and add a script to your package.json.
Initialize Configuration:
npx sc-prisma-extractor --initCustomize
prisma-extractor.json:{ "$schema": "./prisma-extractor.schema.json", "prismaSchema": "./prisma/schema.prisma", "outputFile": "./src/generated/types.ts", "generateMetadata": true, "outputType": "interface", "enumOutputType": "enum" }Add a script to
package.json:"scripts": { "prisma:generate-types": "sc-prisma-extractor" }Run the script:
npm run prisma:generate-types
Configuration
SC Prisma Extractor is highly customizable through a prisma-extractor.json file.
Generating a Configuration File
To create a default configuration file, use the --init flag:
npx sc-prisma-extractor --initThis generates a prisma-extractor.json file with default values.
Configuration File Structure
The configuration file (prisma-extractor.json) allows you to control paths, output formats, and type generation behavior.
{
"$schema": "./prisma-extractor.schema.json",
"prismaSchema": "./prisma/schema.prisma",
"outputFile": "./src/generated/types.ts",
"generateMetadata": false,
"outputType": "interface",
"enumOutputType": "enum",
"relationFieldsIsOptional": true,
"defaultIsOptional": true,
"idIsOptional": true,
"idType": "string",
"mapTypes": {
"String": "string",
"Int": "number",
"Float": "number",
"BigInt": "bigint",
"Boolean": "boolean",
"DateTime": "Date",
"Json": "string",
"Decimal": "number",
"Bytes": "Buffer",
"Unsupported": "unknown"
}
}Configuration Options
prismaSchema: Path to your Prisma schema file.outputFile: Path for the generated TypeScript file.generateMetadata: Iftrue, creates ametadata.jsonfile with DMMF details.outputType: Defines the output for models ("interface"or"type").enumOutputType: Defines the output for enums ("enum"or"type").mapTypes: A dictionary to map Prisma scalar types to custom TypeScript types.relationFieldsIsOptional: Iftrue, marks relation fields (e.g.,posts: Post[]) as optional.defaultIsOptional: Iftrue, fields with a@defaultvalue become optional.idIsOptional: Iftrue,@idfields are marked as optional.idType: Overrides the type for@idfields to be"string"or"number".
Customizing Type Mappings and Output
You can modify the mapTypes object and other options to fit your needs:
{
"outputType": "type",
"enumOutputType": "type",
"mapTypes": {
"DateTime": "string",
"Json": "any",
"Bytes": "Uint8Array"
}
}Using a Custom Configuration File
By default, the tool looks for prisma-extractor.json in the current working directory. You can specify a different path using the --config option:
npx sc-prisma-extractor --config ./config/my-custom-config.json ./prisma/schema.prisma ./src/generated/types.tsYou can also combine --init with --config to generate the configuration file in a custom location:
npx sc-prisma-extractor --init --config ./config/my-custom-config.jsonConfiguration Priority
- If a configuration file is found, its mappings are merged with the defaults
- Custom mappings in the configuration file override the defaults
- If no configuration file is found, the tool uses the built-in default mappings
- Unknown Prisma types fall back to using the Prisma type name as-is
Configuration Validation
SC Prisma Extractor includes built-in validation for the configuration file to help developers detect errors early.
Automatic Validation
The tool automatically validates the configuration file when loading it. If the file is invalid, the extraction will fail with a clear error message.
Manual Validation
You can validate your configuration file independently using:
npm run validate-configThis will check the prisma-extractor.json file and report any validation errors.
Validation Rules
The validator checks:
- mapTypes: Must be an object with string values
- outputType: Must be
"interface"or"type" - Structure: No unexpected properties allowed
- JSON: Valid JSON syntax
Example Error Messages
🟥 Invalid configuration: outputType must be one of the following: interface, type; Unexpected property: invalidProperty.Example Configuration
See prisma-extractor.example.json for a complete example of a valid configuration.
Security
SC Prisma Extractor is designed to be a local development tool. To prevent accidental writes to sensitive paths, the tool includes a security check to ensure that all output files are written within the project directory. If an output path outside the project directory is specified, the tool will exit with an error.
JSON Schema for Validation
For automatic validation in editors that support JSON Schema (like VS Code), use the included prisma-extractor.schema.json file. You can reference it at the top of your prisma-extractor.json:
{
"$schema": "./prisma-extractor.schema.json",
"mapTypes": {
"String": "string",
"Int": "number",
"Float": "number",
"BigInt": "bigint",
"Boolean": "boolean",
"DateTime": "Date",
"Json": "string",
"Decimal": "number",
"Bytes": "Buffer",
"Unsupported": "unknown"
},
"outputType": "interface"
}This will provide autocomplete, real-time validation, and inline documentation in your editor.
The command will generate two files in the same directory as the specified output path. For the example npx sc-prisma-extractor ./prisma/schema.prisma ./src/generated/types.ts, the output will be:
./src/generated/types.ts./src/generated/metadata.json
TypeScript Interfaces (types.ts)
This file contains the generated TypeScript enums and interfaces from your schema.
Before (in schema.prisma):
enum Role {
USER
ADMIN
}
model User {
id String @id @default(cuid())
email String @unique
name String?
role Role @default(USER)
posts Post[]
createdAt DateTime @default(now())
}
model Post {
id String @id @default(cuid())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId String
createdAt DateTime @default(now())
}After (in src/generated/types.ts with outputType: "interface"):
export enum Role {
USER = "USER",
ADMIN = "ADMIN",
}
export interface User {
id: string;
email: string;
name: string | null;
role: Role;
posts: Post[];
createdAt: Date;
}
export interface Post {
id: string;
title: string;
content: string | null;
published: boolean;
author: User;
authorId: string;
createdAt: Date;
}Or with outputType: "type":
export enum Role {
USER = "USER",
ADMIN = "ADMIN",
}
export type User = {
id: string;
email: string;
name: string | null;
role: Role;
posts: Post[];
createdAt: Date;
};
export type Post = {
id: string;
title: string;
content: string | null;
published: boolean;
author: User;
authorId: string;
createdAt: Date;
};Metadata (metadata.json)
This file contains the complete Prisma DMMF (Data Model Meta Format) metadata. This is useful for advanced scripts or tools that need a machine-readable version of your schema. You can use it to build your own generators, validation libraries, or any other tool that needs deep introspection of your data model.
Development Workflow
To test and develop this tool locally on your machine:
- Clone the repository.
- Install dependencies:
npm install - Link the package: This makes the
sc-prisma-extractorcommand available globally, pointing to your local source code.npm link - Develop: Make your changes in the
src/directory. - Compile: After making changes, you should recompile the TypeScript code.
npm run build - Test: The
sc-prisma-extractorcommand now runs your latest compiled code. You can test it from any directory.
Contribution
Contributions are welcome! Please see the CONTRIBUTING.md file for guidelines.
