GithubHelp home page GithubHelp logo

adeyahya / prisma-typebox-generator Goto Github PK

View Code? Open in Web Editor NEW
22.0 1.0 20.0 174 KB

typebox ( typescript static type & json schema ) generator for Prisma 2

License: MIT License

JavaScript 2.03% TypeScript 97.97%
prisma schema typebox static-typing prisma-generator ajv json-validator

prisma-typebox-generator's Introduction

Actions Status npm GitHub license semantic-release Open Source? Yes!

Prisma Typebox Generator

A generator, which takes a Prisma 2 schema.prisma and generates a typebox snippets.

Getting Started

1. Install

npm:

npm install prisma-typebox-generator --save-dev

yarn:

yarn add -D prisma-typebox-generator

2. Add the generator to the schema

generator typebox {
  provider = "prisma-typebox-generator"
}

With a custom output path (default=./typebox)

generator typebox {
  provider = "prisma-typebox-generator"
  output = "custom-output-path"
}

3. Run generation

prisma:

prisma generate

nexus with prisma plugin:

nexus build

Supported Node Versions

Node Version Support
(Maintenance LTS) 10 ✔️
(Active LTS) 12 ✔️
(Current) 14 ✔️

Examples

This generator converts a prisma schema like this:

datasource db {
	provider = "postgresql"
	url      = env("DATABASE_URL")
}

model User {
    id          Int      @id @default(autoincrement())
    createdAt   DateTime @default(now())
    email       String   @unique
    weight      Float?
    is18        Boolean?
    name        String?
    successorId Int?
    successor   User?    @relation("BlogOwnerHistory", fields: [successorId], references: [id])
    predecessor User?    @relation("BlogOwnerHistory")
    role        Role     @default(USER)
    posts       Post[]
    keywords    String[]
    biography   Json
}

model Post {
    id     Int   @id @default(autoincrement())
    user   User? @relation(fields: [userId], references: [id])
    userId Int?
}

enum Role {
    USER
    ADMIN
}

License: MIT

Copyright (c) 2022 Ade Yahya Prasetyo

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

prisma-typebox-generator's People

Contributors

adeyahya avatar fauh45 avatar joemckenney avatar semantic-release-bot avatar tldmain avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

prisma-typebox-generator's Issues

Naming conflict of exported member. Cannot use the word `Type` in schema.prisma

Hi!

First of all, thanks for creating this. It's a great tool! One issue though and likely it's with my naming of things, but I want to just see if there's something here that could be improved as I didn't foresee this issue when i created my prisma schema.

I have a schema.prisma which looks partly like this:

enum ComponentType {
  Select
  Text
}

model Component {
  id            String        @id @default(dbgenerated("uuid_generate_v4()")) @db.Uuid
  name          String
  type          ComponentType
  company       Company       @relation(fields: [companyId], references: [id])
  companyId     String        @db.Uuid
  componentData Json
}

The outputted index file from it looks like this:

.....
export * from './Component';
export * from './CompanyInput';
export * from './ComponentType';
....

This produces a problem in the outputted index.ts file like so:
prisma-typebox-1

Component.ts

import { Type, Static } from "@sinclair/typebox";
import { ComponentType } from "./ComponentType";

export const ComponentInput = Type.Object({
  id: Type.String(),
  name: Type.String(),
  type: ComponentType,
  company: Type.Object({
    id: Type.String(),
    name: Type.String(),
  }),
  companyId: Type.String(),
  componentData: Type.String(),
});

export type ComponentInputType = Static<typeof ComponentInput>;

Because the file Component gets a generated type called ComponentType. This of course is something that is what it is but perhaps a thing to note in the readme (unless i missed it and it's already there).

I can of course get around this with naming my enum something like ComponentEnum instead

Optional Relationship Typebox Bug

On relationship shown below, where the user attribute are optional.

model Post {
  id     Int   @id @default(autoincrement())
  user   User? @relation(fields: [userId], references: [id])
  userId Int?
}

It will produces typebox typings like shown below,

export const Post = Type.Object({
  id: Type.Number(),
  user: Type.Optional(
    Type.Object({
      id: Type.Number(),
      createdAt: Type.Optional(Type.String()),
      email: Type.String(),
      weight: Type.Optional(Type.Number()),
      is18: Type.Optional(Type.Boolean()),
      name: Type.Optional(Type.String()),
      successorId: Type.Optional(Type.Number()),
      role: Type.Optional(Role),
      keywords: Type.Array(Type.String()),
      biography: Type.String(),
      decimal: Type.Number(),
      biginteger: Type.Integer(),
    })
  ),
  userId: Type.Optional(Type.Number()),
});

Notice where the user attribute uses Type.Optional( ... ), but for object as the typebox readme described,

image

Don't you think it should use Type.Partial( ... ) instead?

Entity without relations?

Is it possible to create each entity in a version without its relations? In many cases I don't need the relations inside the type and will do something like this to omit them:

export const DomainNoRelations = t.Omit(Domain, [
  "app",
  "users",
  "resourceBasedAppAccesses",
  "roleBasedAppAccesses",
]);

Having each entity stripped of its related entities would really help! Thanks for your work!

Error on Type "BigInt"

Having BigInt type in the schema results in error "SyntaxError: Binding should be performed on object property. (9:7)"

image

Optional types in query results derive from typescript type

When I have this model

model AgendaItem {
  id           String         @id @default(uuid())
  title        String
  description  String?
}

with a generated schema like this:

export const AgendaItem = Type.Object(
  {
    id: Type.String(),
    title: Type.String(),
    description: Type.Optional(Type.String()),
  }
);

and I run a query like this:

await db.agendaItem.findMany();

the returned type is incompatible since the

export type AgendaItemType = Static<typeof AgendaItem>;

expects the description field to be of type string | undefined but the query returns a type with a description of type string | null which makes sense from a DB perspective.

Extended validation options

Is there a way to e.g. validate email inputs via the config object on the String validator?

const T = Type.String({
  format: 'email'
}) 

doesn't run on pnpm

Error: Generator at prisma-typebox-generator could not start:

/bin/sh: prisma-typebox-generator: command not found

 ERROR  Command failed with exit code 1: /Users/adeyahya/Library/pnpm/store/v3/tmp/dlx-89483/node_modules/.bin/prisma generate

pnpm: Command failed with exit code 1: /Users/adeyahya/Library/pnpm/store/v3/tmp/dlx-89483/node_modules/.bin/prisma generate
    at makeError (/Users/adeyahya/.volta/tools/image/packages/pnpm/lib/node_modules/pnpm/dist/pnpx.cjs:16527:17)
    at handlePromise (/Users/adeyahya/.volta/tools/image/packages/pnpm/lib/node_modules/pnpm/dist/pnpx.cjs:17098:33)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async Object.handler [as dlx] (/Users/adeyahya/.volta/tools/image/packages/pnpm/lib/node_modules/pnpm/dist/pnpx.cjs:183480:7)
    at async /Users/adeyahya/.volta/tools/image/packages/pnpm/lib/node_modules/pnpm/dist/pnpx.cjs:192579:21
    at async run (/Users/adeyahya/.volta/tools/image/packages/pnpm/lib/node_modules/pnpm/dist/pnpx.cjs:192553:34)
    at async /Users/adeyahya/.volta/tools/image/packages/pnpm/lib/node_modules/pnpm/dist/pnpx.cjs:192625:5

DateTime is typed as string?

Using the generator, DateTime fields are typed as Type.String() even though, prisma returns them as js Date objects. Is there a way to change that?

Option to hide fields only from input

Hi, thanks for the great job!

Is there an option to hide fields from input only?

@typebox.hide - hides from everywhere, perhaps I didn't notice it in the source code...

Thank you in advance!

Customize import/export syntax

My project is completely converted to using ESM, so imports without an extension are failing. It would be nice if there was a flag that changed the output along these lines:

// Before
export * from './SomeType';
export * from './SomeOtherType';
...
// After
export * from './SomeType.js';
export * from './SomeOtherType.js';
...

@id field is converted to optional

Thanks for making a good package.
I found what I think is probably a malfunction, so I will report it.

I tried to convert this model.

model Todo {
  id    Int    @default(autoincrement()) @id
  title String
}

Result

export const Todo = Type.Object({
  id: Type.Optional(Type.Number()),
  title: Type.String(),
});

id field is converted to Type.Optional(Type.Number()).

According to the prisma reference, @id cannot be optional.
https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference/#id

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.