@panter/prisma-inputs
v1.0.2
Published
Prisma Inputs is a TypeScript library that provides utility functions and types for working with Prisma input schemas. It offers a set of mapper functions that help you map and transform a model that can be used in a form to match the structure expected b
Downloads
235
Keywords
Readme
Prisma Inputs
Prisma Inputs is a TypeScript library that provides utility functions and types for working with Prisma input schemas. It offers a set of mapper functions that help you map and transform a model that can be used in a form to match the structure expected by Prisma's create
, update
, connect
and disconnect
methods.
Installation
yarn add @panter/prisma-inputs
! Important NOTE !
This package is not transpiled
jet.
If you want to use it with next js you need to add this to your next.config.js
:
const nextConfig = {
transpilePackages: ["@panter/prisma-inputs"]
...
}
Understanding Prisma Inputs
The Problem
When working with Prisma, there's a fundamental mismatch between how we model data in our application layer and how Prisma expects input for its operations. This becomes especially apparent when dealing with:
1. Nested Relations
Prisma requires specific structures for creating, updating, or connecting related entities:
// Your application model
const user = {
name: 'John',
profile: {
bio: 'Developer',
},
};
// What Prisma expects
const prismaInput = {
name: 'John',
profile: {
create: {
bio: 'Developer',
},
},
};
2. Update Operations:
Prisma uses a special set operator for updates:
// Your application update
const update = {
name: 'Jane',
};
// What Prisma expects
const prismaUpdate = {
name: { set: 'Jane' },
};
3. Reference Handling
Converting between direct references and Prisma's connect/disconnect operations:
// Your model
const post = {
author: { id: '123' },
};
// Prisma's expectation
const prismaPost = {
author: {
connect: { id: '123' },
},
};
The Solution
Prisma Inputs provides a declarative way to define mappings between your application models and Prisma's input requirements using automatic mappers that infer types correctly.
1. Schema Definition with Auto-Mappers
const userSchema = prismaSchemaBuilder<UserCreateInput, UserUpdateInput, User>({
props: {
name: autoProperty({ set: true }),
email: autoProperty({ set: true }),
profile: autoRelation(() => profileSchema.relation()),
group: autoReference(),
roles: autoManyReference(),
},
create: {
// Create-specific mappings
},
update: {
// Update-specific mappings
},
});
2. Type-Safe Automatic Transformations
The library provides several automatic mappers that infer types from your model:
// Property Mapper
autoProperty<Input, ModelSource, Key>({ set?: boolean })
// Relation Mapper
autoRelation<T extends { create?: any; update?: any }>()
// Reference Mapper
autoReference<Input extends GenericPrismaOneConnect, ModelSource, Key>()
// Many Reference Mapper
autoManyReference<T extends GenericPrismaOneConnect, S, ModelSource, Key>()
Each mapper intelligently infers types from your model and ensures type safety throughout the transformation process.
3. Relationship Handling
The library supports various relationship patterns with automatic type inference:
type UserModel = {
id: string;
profile: Profile;
groups: Group[];
role?: Role | null;
};
const schema = prismaSchemaBuilder<UserCreateInput, UserUpdateInput, UserModel>(
{
props: {
// One-to-One relation with automatic type inference
profile: autoRelation(() => profileSchema.relation()),
// Many-to-Many with automatic reference handling
groups: autoManyReference(),
// Optional relation with proper null handling
role: autoReference(),
},
},
);
Key Features
Type Safety and Inference
Automatic type inference from your model to Prisma inputs Proper handling of nullable and optional fields Type checking for nested structures and relationships Compile-time validation of mapping configurations
Smart Mapping System
- Property Mapping
<<<<<<< Updated upstream
// Automatically maps and infers types from your model
autoProperty<Input, ModelSource, Key>({ set: true });
=======
const user: UserModel = {
name: "John Doe",
email: "[email protected]",
address: {
id: "1",
street: "123 Main St",
city: "Anytown",
zip: "12345"
}
};
<<<<<<< Updated upstream
=======
const schema = prismaSchemaBuilder<UserCreateInput, UserUpdateInput, UserModel>(
{
props: {
// One-to-One relation with automatic type inference
profile: autoRelation(() => profileSchema.relation()),
// One-to-One reference for relations with automatic type inference
//profile: autoRelation(() => profileSchema.relation()),
// Many-to-Many with automatic reference handling
groups: autoManyReference(),
// Optional relation with proper null handling
role: autoReference(),
},
},
);
>>>>>>> Stashed changes
>>>>>>> Stashed changes
- Relation Mapping
// Handles create/update/connect operations automatically
autoRelation<T>(() => ({
create: () => createSchema,
update: () => updateSchema,
}));
- Reference Handling
// Automatically handles connect/disconnect operations
autoReference<Input, ModelSource, Key>();
Why Use This Library?
- Type Inference: Leverages TypeScript's type system to automatically infer correct types from your models to Prisma inputs.
- Automatic Mapping: Provides smart mappers that handle common transformation patterns automatically.
- GraphQL Integration: Seamlessly integrates with GraphQL operations through the resource builder.
- Performance: Implements efficient diffing for updates and smart handling of relationships.
- Developer Experience: Reduces boilerplate while maintaining type safety and providing excellent IDE support.
Architecture Benefits
- Clear separation between domain models and Prisma inputs
- Automatic type inference reduces potential errors
- Consistent handling of Prisma operations
- Extensible mapping system for custom requirements
The library solves the impedance mismatch between your domain models and Prisma's input requirements while providing excellent type safety and developer experience through its automatic mapping system.
Usage
To use Prisma Inputs, you need to import the necessary functions and types from the library. Here's an example of how you can use Prisma Inputs to define an input schema and map input data:
PrismaInputSchema
import {
PrismaInputSchema,
PropertyMapper,
OneRelationMapper,
reference,
relation,
object,
autoProperty,
autoManyRelation,
autoManyReference,
autoReference,
autoManyReference,
mapFromPrismaSchema,
} from '@panter/prisma-inputs';
// Create an input schema
const addressCreateSchema: PrismaInputSchema<
AddressCreateWithoutPersonInput,
InferPrismaModel<Partial<AddressCreateWithoutPersonInput>>
> = {
mapper: object(),
properties: {
address: autoProperty({ set: true }),
},
};
// Update an input schema
const addressUpdateSchema: PrismaInputSchema<
AddressUpdateInput,
InferPrismaModel<Partial<AddressUpdateInput>>
> = {
mapper: object(),
properties: {
address: autoProperty({ set: true }),
},
};
// create a new address
const createAddressInput = mapFromPrismaSchema({
schema: addressCreateSchema,
value: { address: 'otherstreet' },
});
console.log(createAddressInput); // { address: 'otherstreet' }
// update new address
const newAddress = { id: '1', address: 'streetname' };
const updateAddressInput = mapFromPrismaSchema({
schema: addressUpdateSchema,
value: newAddress,
});
console.log(updateAddressInput); // { address: { set: 'streetname' } }
// use address schema in a relation
const userCreateSchema: PrismaInputSchema<PersonCreateInput> = {
mapper: object(),
properties: {
name: property(),
name: autoProperty({ set: true }),
addresses: autoManyRelation(() => addressSchema.relation()),
organization: autoReference(),
},
};
const createPersonInput = mapFromPrismaSchema({
schema: userCreateSchema,
value: { organisation: { id: '1' }, addresses: [{ address: 'streetname' }] },
});
/**
{
organisation: { connect: { id: '1' } },
addresses: { create: [{ address: 'streetname' }] },
}
*/
console.log(createPersonInput);
PrismaSchemaBuilder
To define an input schema builder, you can use the prismaSchema function. It takes three parameters: unionProps, createProps, and updateProps. These parameters are functions that define the properties of the input schema.
Here's an example of how to define an input schema for the Simple model:
const simpleSchema = prismaSchemaBuilder<SimpleCreateInput, SimpleUpdateInput>({
props: {
name: property(),
},
create: {},
update: { secondName: property() },
});
const personSchema = prismaSchemaBuilder<PersonCreateInput, PersonUpdateInput>({
props: {
name: autoProperty({ set: true }),
addresses: autoManyRelation(() => addressSchema.relation()),
organization: autoReference(),
},
create: {},
update: {},
});
const addressSchema = prismaSchemaBuilder<
AddressCreateWithoutPersonInput,
AddressUpdateInput
>({
props: {
address: autoProperty({ set: true }),
},
create: {},
update: {},
});
const organisationCreateMapper: PrismaInputSchema<
PrismaInput<OrganisationCreateInput>
> = {
mapper: object(),
properties: {
description: autoProperty({ set: true }),
persons: autoManyReference(),
simple: autoRelation(() => simpleSchema.relation()),
simples: autoManyRelation(() => simpleSchema.relation()),
},
};
Using the schemas to map
describe('mapFromPrismaSchema()', () => {
it('should map using the schema', () => {
const createSchema = personSchema.createSchema;
expect(createSchema).not.toBeUndefined();
if (!createSchema) {
return;
}
const resultCreate = mapFromPrismaSchema({
schema: createSchema,
value: { addresses: [{ id: '1' }] },
});
expect(resultCreate).toEqual({
addresses: { connect: [{ id: '1' }] },
});
});
});
Demo
In the file demo.ts
you can see a full example of how to use the library.
To run the demo:
npx tsx demo.ts