npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@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

399

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

  1. 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
  1. Relation Mapping
// Handles create/update/connect operations automatically
autoRelation<T>(() => ({
  create: () => createSchema,
  update: () => updateSchema,
}));
  1. 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