Skip to content

Commit

Permalink
fix: Adapted to Prisma 2.20
Browse files Browse the repository at this point in the history
BREAKING CHANGE:
Adapted to Prisma 2.20

closes: unlight#17
  • Loading branch information
unlight committed Mar 31, 2021
1 parent ab5c592 commit c5f040d
Show file tree
Hide file tree
Showing 16 changed files with 122 additions and 59 deletions.
22 changes: 11 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
}
},
"dependencies": {
"@prisma/generator-helper": "^2.19.0",
"@prisma/generator-helper": "^2.20.0",
"await-event-emitter": "^2.0.2",
"filenamify": "^4.2.0",
"flat": "^5.0.2",
Expand All @@ -70,7 +70,7 @@
"@nestjs/graphql": "^7.10.3",
"@nestjs/platform-express": "^7.6.15",
"@paljs/plugins": "^2.13.0",
"@prisma/client": ">=2.19",
"@prisma/client": "2.20.0",
"@semantic-release/changelog": "^5.0.1",
"@semantic-release/git": "^9.0.0",
"@types/find-cache-dir": "^3.2.0",
Expand All @@ -79,26 +79,26 @@
"@types/mocha": "^8.2.2",
"@types/node": "^14.14.37",
"@types/pluralize": "^0.0.29",
"@typescript-eslint/eslint-plugin": "^4.19.0",
"@typescript-eslint/parser": "^4.19.0",
"apollo-server-express": "^2.22.1",
"c8": "^7.6.0",
"@typescript-eslint/eslint-plugin": "^4.20.0",
"@typescript-eslint/parser": "^4.20.0",
"apollo-server-express": "^2.22.2",
"c8": "^7.7.0",
"class-transformer": "^0.4.0",
"class-validator": "^0.13.1",
"commitizen": "^4.2.3",
"cz-customizable": "^6.3.0",
"decimal.js": "^10.2.1",
"eslint": "^7.23.0",
"eslint-import-resolver-node": "^0.3.4",
"eslint-plugin-etc": "^1.3.7",
"eslint-plugin-etc": "^1.3.8",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-only-warn": "^1.0.2",
"eslint-plugin-prettier": "^3.3.1",
"eslint-plugin-promise": "^4.3.1",
"eslint-plugin-regexp": "^0.6.3",
"eslint-plugin-simple-import-sort": "^7.0.0",
"eslint-plugin-sonarjs": "^0.6.0",
"eslint-plugin-sort-class-members": "^1.10.0",
"eslint-plugin-sort-class-members": "^1.11.0",
"eslint-plugin-total-functions": "^4.7.2",
"eslint-plugin-unicorn": "^29.0.0",
"eslint-plugin-wix-editor": "^3.3.0",
Expand All @@ -108,12 +108,12 @@
"graphql": "^15.5.0",
"graphql-type-json": "^0.3.2",
"mocha": "^8.3.2",
"ololog": "^1.1.174",
"ololog": "^1.1.175",
"precise-commits": "^1.0.2",
"prettier": "^2.2.1",
"prisma": "2.19.0",
"prisma": "2.20.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^6.6.6",
"rxjs": "^6.6.7",
"semantic-release": "^17.4.2",
"simplytyped": "^3.3.0",
"ts-node": "^9.1.1",
Expand Down
2 changes: 1 addition & 1 deletion prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ datasource database {

generator client {
provider = "prisma-client-js"
previewFeatures = ["groupBy", "createMany", "orderByRelation"]
previewFeatures = ["orderByRelation", "selectRelationCount"]
}

generator nestgraphql {
Expand Down
13 changes: 13 additions & 0 deletions src/@generated/article/article-count.output.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Field, Int, ObjectType } from '@nestjs/graphql';

@ObjectType()
export class ArticleCount {
@Field(() => Int, { nullable: false })
tags!: number;

@Field(() => Int, { nullable: false })
favoritedBy!: number;

@Field(() => Int, { nullable: false })
comments!: number;
}
4 changes: 4 additions & 0 deletions src/@generated/article/article.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Field, ID, Int, ObjectType } from '@nestjs/graphql';
import { Comment } from '../comment/comment.model';
import { Tag } from '../tag/tag.model';
import { User } from '../user/user.model';
import { ArticleCount } from './article-count.output';

@ObjectType()
export class Article {
Expand Down Expand Up @@ -47,4 +48,7 @@ export class Article {

@Field(() => Boolean, { nullable: true, defaultValue: true })
active?: boolean;

@Field(() => ArticleCount, { nullable: true })
_count?: ArticleCount;
}
7 changes: 7 additions & 0 deletions src/@generated/tag/tag-count.output.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Field, Int, ObjectType } from '@nestjs/graphql';

@ObjectType()
export class TagCount {
@Field(() => Int, { nullable: false })
articles!: number;
}
4 changes: 4 additions & 0 deletions src/@generated/tag/tag.model.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Field, ID, ObjectType } from '@nestjs/graphql';

import { Article } from '../article/article.model';
import { TagCount } from './tag-count.output';

@ObjectType()
export class Tag {
Expand All @@ -12,4 +13,7 @@ export class Tag {

@Field(() => [Article], { nullable: true })
articles?: Array<Article>;

@Field(() => TagCount, { nullable: true })
_count?: TagCount;
}
19 changes: 19 additions & 0 deletions src/@generated/user/user-count.output.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Field, Int, ObjectType } from '@nestjs/graphql';

@ObjectType()
export class UserCount {
@Field(() => Int, { nullable: false })
following!: number;

@Field(() => Int, { nullable: false })
followers!: number;

@Field(() => Int, { nullable: false })
favoriteArticles!: number;

@Field(() => Int, { nullable: false })
articles!: number;

@Field(() => Int, { nullable: false })
comments!: number;
}
4 changes: 4 additions & 0 deletions src/@generated/user/user.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Field, Float, HideField, ID, Int, ObjectType } from '@nestjs/graphql';
import { Article } from '../article/article.model';
import { Comment } from '../comment/comment.model';
import { Role } from '../prisma/role.enum';
import { UserCount } from './user-count.output';

@ObjectType()
export class User {
Expand Down Expand Up @@ -47,4 +48,7 @@ export class User {

@Field(() => Role, { nullable: true })
role?: Role;

@Field(() => UserCount, { nullable: true })
_count?: UserCount;
}
20 changes: 11 additions & 9 deletions src/generate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import AwaitEventEmitter from 'await-event-emitter';
import expect from 'expect';
import {
ClassDeclaration,
Decorator,
EnumDeclarationStructure,
Project,
PropertyDeclarationStructure,
Expand Down Expand Up @@ -755,20 +754,16 @@ describe('one model with self reference', () => {
await testGenerate({
schema: `model User {
id Int @id
parent User @relation("UserToUser", fields: [userId], references: [id])
User User[] @relation("UserToUser")
userId Int
parentId Int
parent User @relation("UserToUser", fields: [parentId], references: [id])
user User[] @relation("UserToUser")
}`,
});
});

describe('model', () => {
before(() => {
sourceFile = project.getSourceFile(s =>
s.getFilePath().endsWith('user.model.ts'),
)!;
sourceText = sourceFile.getText();
imports = getImportDeclarations(sourceFile);
setSourceFile('user.model.ts');
});

// it('', () => console.log('sourceText', sourceText));
Expand All @@ -778,6 +773,13 @@ describe('one model with self reference', () => {
expect.objectContaining({ name: 'User' }),
);
});

it('imports should contain user count', () => {
expect(imports).toContainEqual({
name: 'UserCount',
specifier: './user-count.output',
});
});
});

describe('user list relation filter', () => {
Expand Down
10 changes: 6 additions & 4 deletions src/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ export async function generate(
eventEmitter.emitSync('Warning', message);
}
const prismaClientOutput = otherGenerators.find(
x => x.provider === 'prisma-client-js',
)?.output;
x => x.provider.value === 'prisma-client-js',
)?.output?.value;

assert(prismaClientOutput, 'Cannot find output of prisma-client-js');

Expand Down Expand Up @@ -94,7 +94,7 @@ export async function generate(
const fieldSettings = new Map<string, Map<string, FieldSettings>>();
const getModelName = createGetModelName(modelNames);
const getSourceFile = factoryGetSourceFile({
output: generator.output,
output: generator.output.value,
project,
getModelName,
outputFilePattern: config.outputFilePattern,
Expand All @@ -111,14 +111,16 @@ export async function generate(
modelFields,
fieldSettings,
project,
output: generator.output,
output: generator.output.value,
getSourceFile,
eventEmitter,
typeNames: new Set<string>(),
enums: mapKeys(datamodel.enums, x => x.name),
getModelName: createGetModelName(modelNames),
};

// console.dir(prismaClientDmmf.schema.outputObjectTypes, { depth: 4 });

if (connectCallback) {
await connectCallback(eventEmitter, eventArguments);
}
Expand Down
9 changes: 2 additions & 7 deletions src/handlers/args-type.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { getModelName } from '../helpers/get-model-name';
import { pascalCase } from '../helpers/pascal-case';
import { EventArguments, InputType, SchemaField } from '../types';

Expand All @@ -10,13 +9,9 @@ export function argsType(field: SchemaField, args: EventArguments) {
if (['queryRaw', 'executeRaw'].includes(field.name)) {
return;
}
const { eventEmitter, modelNames, typeNames } = args;
const { eventEmitter, typeNames, getModelName } = args;
const className = pascalCase(`${field.name}Args`);
const modelName =
getModelName({
name: className,
modelNames,
}) || '';
const modelName = getModelName(className) || '';
const inputType: InputType = {
// eslint-disable-next-line unicorn/no-null
constraints: { maxNumFields: null, minNumFields: null },
Expand Down
39 changes: 24 additions & 15 deletions src/handlers/model-output-type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {

import { getGraphqlImport } from '../helpers/get-graphql-import';
import { getGraphqlType } from '../helpers/get-graphql-type';
import { getOutputTypeName } from '../helpers/get-output-type-name';
import { getPropertyType } from '../helpers/get-property-type';
import { ImportDeclarationMap } from '../helpers/import-declaration-map';
import { propertyStructure } from '../helpers/property-structure';
Expand All @@ -19,18 +20,16 @@ export function modelOutputType(outputType: OutputType, args: EventArguments) {
const { getSourceFile, models, config, modelFields, fieldSettings } = args;
const model = models.get(outputType.name);
assert(model, `Cannot find model by name ${outputType.name}`);
const fileType = 'model';
const sourceFile = getSourceFile({
name: outputType.name,
type: fileType,
type: 'model',
});

const sourceFileStructure = sourceFile.getStructure();

const importDeclarations = new ImportDeclarationMap();
let classStructure = (sourceFileStructure.statements as StatementStructures[]).find(
(s: StatementStructures) => s.kind === StructureKind.Class,
) as ClassDeclarationStructure | undefined;

if (!classStructure) {
classStructure = {
kind: StructureKind.Class,
Expand Down Expand Up @@ -62,21 +61,18 @@ export function modelOutputType(outputType: OutputType, args: EventArguments) {
continue;
}

const { location, isList, type } = field.outputType;
const outputTypeName = String(type);
let fileType = 'model';
const { location, isList, type, namespace } = field.outputType;

let outputTypeName = String(type);
if (namespace !== 'model') {
fileType = 'output';
outputTypeName = getOutputTypeName(outputTypeName);
}
const customType = config.types[outputTypeName];
const modelField = modelFields.get(model.name)?.get(field.name);
const settings = fieldSettings.get(model.name)?.get(field.name);

// console.log({
// 'field.outputType': field.outputType,
// 'outputType.name': outputType.name,
// 'model?.name': model?.name,
// outputTypeName,
// 'field.name': field.name,
// fieldMeta,
// });

const propertyType = customType?.fieldType
? [customType.fieldType]
: getPropertyType({
Expand All @@ -102,6 +98,19 @@ export function modelOutputType(outputType: OutputType, args: EventArguments) {
getSourceFile,
});

// console.log({
// 'field.outputType': field.outputType,
// 'outputType.name': outputType.name,
// 'model.name': model.name,
// outputTypeName,
// 'field.name': field.name,
// settings,
// propertyType,
// graphqlType,
// graphqlImport,
// location,
// });

const property = propertyStructure({
name: field.name,
isNullable: field.isNullable,
Expand Down
5 changes: 0 additions & 5 deletions src/helpers/get-graphql-import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,5 @@ export function getGraphqlImport(args: {
}).getFilePath(),
);

if (specifier.includes('output-count-aggregate.model')) {
console.trace('wrong name');
throw 1;
}

return { name, specifier };
}
10 changes: 9 additions & 1 deletion src/helpers/get-model-name.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export function createGetModelName(modelNames: string[]) {
}
}

export function getModelName(args: {
function getModelName(args: {
name: string;
modelNames: string[];
}): string | undefined {
Expand All @@ -31,6 +31,13 @@ export function getModelName(args: {
return test;
}
}
// test for {Model}Count
if (name.slice(-5) === 'Count') {
const test = name.slice(0, -5);
if (modelNames.includes(test)) {
return test;
}
}
// eslint-disable-next-line consistent-return, unicorn/no-useless-undefined
return undefined;
}
Expand Down Expand Up @@ -69,6 +76,7 @@ const splitKeywords = [
'UncheckedUpdate',
'UncheckedCreate',
'ScalarWhere',
'CountOutputType',
].sort((a, b) => b.length - a.length);

const endsWithKeywords = [
Expand Down
Loading

0 comments on commit c5f040d

Please sign in to comment.