Skip to content

Commit

Permalink
tests and config
Browse files Browse the repository at this point in the history
  • Loading branch information
ogroppo committed Nov 25, 2024
1 parent 8f138e8 commit b1dc4df
Show file tree
Hide file tree
Showing 14 changed files with 988 additions and 602 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
"build": "turbo run build",
"ci:publish": "pnpm publish --no-git-checks -r",
"dev": "turbo run dev --parallel --no-cache",
"prepublish": "pnpm build",
"release": "pnpm changeset && pnpm changeset version",
"test": "turbo run test"
},
Expand Down
6 changes: 6 additions & 0 deletions packages/prisma-client-types-generator/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# prisma-client-types-generator

## 0.1.0

### Minor Changes

- add test and config

## 0.0.3

### Patch Changes
Expand Down
10 changes: 6 additions & 4 deletions packages/prisma-client-types-generator/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "prisma-client-types-generator",
"version": "0.0.3",
"version": "0.1.0",
"description": "Generate safe types for the browser and other uses",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
Expand All @@ -13,12 +13,13 @@
"dev": "pnpm build --watch",
"lint": "eslint src --fix",
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist",
"prepublish": "pnpm build",
"test": "pnpm prisma generate --schema test/schemas/full.prisma",
"prepublish": "pnpm test && pnpm build",
"test": "sh ./test/test.sh",
"release": "pnpm changeset && pnpm changeset version"
},
"files": [
"/dist"
"/dist",
"test/schemas/full.snapshot.ts"
],
"keywords": [
"prisma",
Expand Down Expand Up @@ -54,6 +55,7 @@
"jest": "^29.7.0",
"prisma": "^5.22.0",
"ts-node": "^10.9.2",
"tsd": "^0.31.2",
"tsup": "^8.3.5",
"tsx": "^4.19.2",
"typescript": "^5.7.2"
Expand Down
24 changes: 24 additions & 0 deletions packages/prisma-client-types-generator/src/formatEntityName.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { PrismaClientTypesGeneratorConfig } from "./onGenerate";

let aliasesMap: Record<string, string> | undefined;

export const formatEntityName = (
rawEntityName: string,
{ aliases, pascalCase }: PrismaClientTypesGeneratorConfig
) => {
if (aliases) {
aliasesMap = aliasesMap || JSON.parse(aliases);
if (rawEntityName in aliasesMap) {
return aliasesMap[rawEntityName];
}
}

if (pascalCase) {
return rawEntityName
.split("_")
.map((s) => s[0].toUpperCase() + s.slice(1))
.join("");
}

return rawEntityName;
};
7 changes: 4 additions & 3 deletions packages/prisma-client-types-generator/src/generateEnum.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { DMMF } from "@prisma/generator-helper";
import { getPascalName } from "./getPascalName";
import { formatEntityName } from "./formatEntityName";
import { PrismaClientTypesGeneratorConfig } from "./onGenerate";

export const generateEnum = (
prismaEnum: DMMF.DatamodelEnum,
aliases?: Record<string, string>
config: PrismaClientTypesGeneratorConfig
) => {
let out = "";

const name = getPascalName(prismaEnum.name, aliases);
const name = formatEntityName(prismaEnum.name, config);

out += `export const ${name} = {\n`;

Expand Down
16 changes: 9 additions & 7 deletions packages/prisma-client-types-generator/src/generateModel.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { DMMF } from "@prisma/generator-helper";
import { getPascalName } from "./getPascalName";
import { formatEntityName } from "./formatEntityName";
import { prismaTypeMap } from "./prismaTypeMap";
import { PrismaClientTypesGeneratorConfig } from "./onGenerate";

const formatNull = (field: DMMF.Field) => {
return !field.isRequired ? " | null" : "";
Expand All @@ -17,11 +18,11 @@ const isBaseField = (field: DMMF.Field, foreignKeysMap: Record<string, 1>) => {

export const generateModel = (
model: DMMF.Model,
aliases?: Record<string, string>
config: PrismaClientTypesGeneratorConfig
) => {
let out = "";

const modelTypeName = getPascalName(model.name, aliases); // TODO: use also model.dbName with alias?
const modelTypeName = formatEntityName(model.name, config); // TODO: use also model.dbName with alias?

// console.log(model.fields);

Expand Down Expand Up @@ -66,9 +67,10 @@ export const generateModel = (
}
switch (field.kind) {
case "enum":
out += ` ${field.name}: ${getPascalName(field.type)}${formatNull(
field
)}\n`;
out += ` ${field.name}: ${formatEntityName(
field.type,
config
)}${formatNull(field)}\n`;
break;
case "scalar":
case "unsupported": // Untested
Expand All @@ -90,7 +92,7 @@ export const generateModel = (
for (const field of model.fields) {
switch (field.kind) {
case "object":
out += ` ${field.name}: ${field.type}${
out += ` ${field.name}: ${formatEntityName(field.type, config)}${
field.isList ? "[]" : ""
}${formatNull(field)}\n`;
break;
Expand Down
11 changes: 4 additions & 7 deletions packages/prisma-client-types-generator/src/generateTypes.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,23 @@
import { DMMF } from "@prisma/generator-helper";
import { generateEnum } from "./generateEnum";
import { generateModel } from "./generateModel";
import { PrismaClientTypesGeneratorConfig } from "./onGenerate";

export const generateTypes = (
datamodel: DMMF.Datamodel,
{
aliases,
}: {
aliases?: Record<string, string>;
}
config: PrismaClientTypesGeneratorConfig
) => {
let file = `// This file was generated by a custom prisma generator, do not edit manually.\n`;

const models = datamodel.models;

for (const model of models) {
file += generateModel(model, aliases);
file += generateModel(model, config);
}

const enums = datamodel.enums;
for (const enumItem of enums) {
file += generateEnum(enumItem, aliases);
file += generateEnum(enumItem, config);
}

return file;
Expand Down
15 changes: 0 additions & 15 deletions packages/prisma-client-types-generator/src/getPascalName.ts

This file was deleted.

25 changes: 11 additions & 14 deletions packages/prisma-client-types-generator/src/onGenerate.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
import type { GeneratorOptions } from "@prisma/generator-helper";
import type {
GeneratorConfig,
GeneratorOptions,
} from "@prisma/generator-helper";
import { generateTypes } from "./generateTypes";
import fs from "node:fs";
import path from "node:path";

export type PrismaClientTypesGeneratorConfig = {
/**
* (./ -> relative to schema, or an importable path to require() it)
*
* @default ./prismaTypes.ts
*/
output?: string;

/**
*
*
Expand All @@ -23,6 +19,9 @@ export type PrismaClientTypesGeneratorConfig = {
* @default undefined
*/
aliases?: string;

// Whether to use PascalCase for the generated types.
pascalCase?: boolean;
};

/** Runs the generator with the given options. */
Expand All @@ -32,12 +31,10 @@ export async function onGenerate(options: GeneratorOptions) {
throw new Error("No output file specified");
}

const aliases =
typeof options.generator.config.aliases === "string"
? JSON.parse(options.generator.config.aliases)
: undefined;

let output = generateTypes(options.dmmf.datamodel, { aliases });
let output = generateTypes(
options.dmmf.datamodel,
options.generator.config as PrismaClientTypesGeneratorConfig
);

const outputPath = path.resolve(outputFile.value);
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
Expand Down
19 changes: 12 additions & 7 deletions packages/prisma-client-types-generator/test/schemas/full.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ generator client {
}

generator types {
provider = "tsx ./src/index"
provider = "tsx ./src/index"
output = "./full.generated.ts"
pascalCase = true
aliases = "{\"Label\":\"Tag\"}"
}

model Post {
Expand All @@ -24,7 +27,7 @@ model Post {
category Category? @relation(fields: [categoryId], references: [id], onDelete: NoAction, onUpdate: NoAction)
categoryId Int?
toMedia PostToMedia[]
tags Tag[]
tags Label[]
user User @relation(fields: [userId], references: [id])
userId String
}
Expand All @@ -48,7 +51,8 @@ model Media {
postToMedias PostToMedia[]
}

model Tag {
// To be aliased
model Label {
id Int @id @default(autoincrement())
name String
createdAt DateTime @default(now())
Expand Down Expand Up @@ -123,7 +127,8 @@ model VerificationToken {
@@unique([identifier, token])
}

model AdminUser {
// To be PascalCased
model admin_user {
id String @id @default(cuid())
name String?
email String? @unique
Expand All @@ -134,13 +139,13 @@ model AdminUser {
}

model Audit {
id String @id @default(cuid())
date DateTime @default(now())
id String @id @default(cuid())
date DateTime @default(now())
resource String
action String
payload Json?
authorId String?
author AdminUser? @relation(fields: [authorId], references: [id], onDelete: Cascade)
author admin_user? @relation(fields: [authorId], references: [id], onDelete: Cascade)
}

enum Role {
Expand Down
Loading

0 comments on commit b1dc4df

Please sign in to comment.