Skip to content

Commit 2a0fe84

Browse files
committed
fix: Change generated enum type to ticked style
1 parent 1f166f7 commit 2a0fe84

11 files changed

+99
-65
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -763,3 +763,4 @@ import { generate } from 'prisma-nestjs-graphql/generate';
763763
- keyof typeof SortOrder -> `SortOrder`
764764
- dummy-createfriends.input.ts -> `create-friends`
765765
- check 'TODO FIXME'
766+
- 22.12 node require esm (update all deps to latest)

src/generate.ts

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ export async function generate(
4242
) => void | Promise<void>;
4343
},
4444
) {
45-
const { connectCallback, generator, skipAddOutputSourceFiles, dmmf } = args;
45+
const { connectCallback, dmmf, generator, skipAddOutputSourceFiles } = args;
4646

4747
const generatorOutputValue = generator.output?.value;
4848
ok(generatorOutputValue, 'Missing generator configuration: output');
@@ -72,12 +72,12 @@ export async function generate(
7272
}
7373

7474
const project = new Project({
75-
tsConfigFilePath: config.tsConfigFilePath,
76-
skipAddingFilesFromTsConfig: true,
77-
skipLoadingLibFiles: !config.emitCompiled,
7875
manipulationSettings: {
7976
quoteKind: QuoteKind.Single,
8077
},
78+
skipAddingFilesFromTsConfig: true,
79+
skipLoadingLibFiles: !config.emitCompiled,
80+
tsConfigFilePath: config.tsConfigFilePath,
8181
});
8282

8383
if (!skipAddOutputSourceFiles) {
@@ -101,30 +101,30 @@ export async function generate(
101101
const fieldSettings = new Map<string, Map<string, ObjectSettings>>();
102102
const getModelName = createGetModelName(modelNames);
103103
const getSourceFile = factoryGetSourceFile({
104-
output: generatorOutputValue,
105-
project,
104+
eventEmitter,
106105
getModelName,
106+
output: generatorOutputValue,
107107
outputFilePattern: config.outputFilePattern,
108-
eventEmitter,
108+
project,
109109
});
110110
const { datamodel, schema } = JSON.parse(JSON.stringify(dmmf)) as Document;
111111
const removeTypes = new Set<string>();
112112
const eventArguments: EventArguments = {
113-
schema,
114-
models,
113+
classTransformerTypeModels: new Set(),
115114
config,
116-
modelNames,
117-
modelFields,
118-
fieldSettings,
119-
project,
120-
output: generatorOutputValue,
121-
getSourceFile,
122-
eventEmitter,
123-
typeNames: new Set<string>(),
124115
enums: mapKeys(datamodel.enums, x => x.name),
116+
eventEmitter,
117+
fieldSettings,
125118
getModelName,
119+
getSourceFile,
120+
modelFields,
121+
modelNames,
122+
models,
123+
output: generatorOutputValue,
124+
project,
126125
removeTypes,
127-
classTransformerTypeModels: new Set(),
126+
schema,
127+
typeNames: new Set<string>(),
128128
};
129129

130130
if (connectCallback) {
@@ -143,7 +143,7 @@ export async function generate(
143143
await eventEmitter.emit('Model', model, eventArguments);
144144
}
145145

146-
const { inputObjectTypes, outputObjectTypes, enumTypes } = schema;
146+
const { enumTypes, inputObjectTypes, outputObjectTypes } = schema;
147147

148148
await eventEmitter.emit('PostBegin', eventArguments);
149149

@@ -170,9 +170,9 @@ export async function generate(
170170
for (const inputType of inputTypes) {
171171
const event = {
172172
...eventArguments,
173-
inputType,
174-
fileType: 'input',
175173
classDecoratorName: 'InputType',
174+
fileType: 'input',
175+
inputType,
176176
};
177177
if (inputType.fields.length === 0) {
178178
removeTypes.add(inputType.name);

src/handlers/generate-files.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { ImportDeclarationMap } from '../helpers/import-declaration-map';
1010
import { EventArguments } from '../types';
1111

1212
export async function generateFiles(args: EventArguments) {
13-
const { project, config, output, eventEmitter } = args;
13+
const { config, eventEmitter, output, project } = args;
1414

1515
if (config.emitSingle) {
1616
const rootDirectory =
@@ -76,9 +76,9 @@ export async function generateFiles(args: EventArguments) {
7676
}
7777
if (statement.defaultImport) {
7878
imports.create({
79+
defaultImport: statement.defaultImport,
7980
from: statement.moduleSpecifier,
8081
name: statement.defaultImport,
81-
defaultImport: statement.defaultImport,
8282
});
8383
}
8484
if (statement.namespaceImport) {
@@ -110,9 +110,9 @@ export async function generateFiles(args: EventArguments) {
110110
project.compilerOptions.set({
111111
declaration: true,
112112
declarationDir: output,
113-
rootDir: output,
114-
outDir: output,
115113
emitDecoratorMetadata: false,
114+
outDir: output,
115+
rootDir: output,
116116
skipLibCheck: true,
117117
});
118118
const emitResult = await project.emit();

src/handlers/output-type.ts

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import { ok } from 'assert';
22
import JSON5 from 'json5';
3-
import { castArray, last } from 'lodash';
3+
import { castArray } from 'lodash';
44
import { ClassDeclarationStructure, StructureKind } from 'ts-morph';
55

6+
import { getEnumName } from '../helpers/get-enum-name';
67
import { getGraphqlImport } from '../helpers/get-graphql-import';
78
import { getOutputTypeName } from '../helpers/get-output-type-name';
89
import { getPropertyType } from '../helpers/get-property-type';
@@ -13,7 +14,7 @@ import { EventArguments, OutputType } from '../types';
1314
const nestjsGraphql = '@nestjs/graphql';
1415

1516
export function outputType(outputType: OutputType, args: EventArguments) {
16-
const { getSourceFile, models, eventEmitter, fieldSettings, getModelName, config } =
17+
const { config, eventEmitter, fieldSettings, getModelName, getSourceFile, models } =
1718
args;
1819
const importDeclarations = new ImportDeclarationMap();
1920

@@ -42,23 +43,23 @@ export function outputType(outputType: OutputType, args: EventArguments) {
4243
});
4344

4445
const classStructure: ClassDeclarationStructure = {
45-
kind: StructureKind.Class,
46-
isExported: true,
47-
name: outputType.name,
4846
decorators: [
4947
{
50-
name: 'ObjectType',
5148
arguments: [],
49+
name: 'ObjectType',
5250
},
5351
],
52+
isExported: true,
53+
kind: StructureKind.Class,
54+
name: outputType.name,
5455
properties: [],
5556
};
5657

5758
importDeclarations.add('Field', nestjsGraphql);
5859
importDeclarations.add('ObjectType', nestjsGraphql);
5960

6061
for (const field of outputType.fields) {
61-
const { location, isList, type } = field.outputType;
62+
const { isList, location, type } = field.outputType;
6263
const outputTypeName = getOutputTypeName(String(type));
6364
const settings = isCountOutput
6465
? undefined
@@ -67,6 +68,7 @@ export function outputType(outputType: OutputType, args: EventArguments) {
6768
name: outputType.name,
6869
output: true,
6970
});
71+
7072
const isCustomsApplicable =
7173
outputTypeName === model?.fields.find(f => f.name === field.name)?.type;
7274

@@ -81,11 +83,11 @@ export function outputType(outputType: OutputType, args: EventArguments) {
8183
);
8284

8385
const property = propertyStructure({
84-
name: field.name,
85-
isNullable: field.isNullable,
8686
hasQuestionToken: isCountOutput ? true : undefined,
87-
propertyType,
8887
isList,
88+
isNullable: field.isNullable,
89+
name: field.name,
90+
propertyType,
8991
});
9092

9193
classStructure.properties?.push(property);
@@ -122,19 +124,17 @@ export function outputType(outputType: OutputType, args: EventArguments) {
122124
} else {
123125
const graphqlImport = getGraphqlImport({
124126
config,
125-
sourceFile,
126127
fileType,
127-
location,
128+
getSourceFile,
128129
isId: false,
130+
location,
131+
sourceFile,
129132
typeName: outputTypeName,
130-
getSourceFile,
131133
});
134+
const referenceName =
135+
location === 'enumTypes' ? getEnumName(propertyType[0]) : propertyType[0];
132136

133137
graphqlType = graphqlImport.name;
134-
let referenceName = propertyType[0];
135-
if (location === 'enumTypes') {
136-
referenceName = last(referenceName.split(' ')) as string;
137-
}
138138

139139
if (
140140
graphqlImport.specifier &&
@@ -143,8 +143,8 @@ export function outputType(outputType: OutputType, args: EventArguments) {
143143
(shouldHideField && referenceName === graphqlImport.name))
144144
) {
145145
importDeclarations.set(graphqlImport.name, {
146-
namedImports: [{ name: graphqlImport.name }],
147146
moduleSpecifier: graphqlImport.specifier,
147+
namedImports: [{ name: graphqlImport.name }],
148148
});
149149
}
150150
}
@@ -153,18 +153,18 @@ export function outputType(outputType: OutputType, args: EventArguments) {
153153

154154
if (shouldHideField) {
155155
importDeclarations.add('HideField', nestjsGraphql);
156-
property.decorators.push({ name: 'HideField', arguments: [] });
156+
property.decorators.push({ arguments: [], name: 'HideField' });
157157
} else {
158158
// Generate `@Field()` decorator
159159
property.decorators.push({
160-
name: 'Field',
161160
arguments: [
162161
isList ? `() => [${graphqlType}]` : `() => ${graphqlType}`,
163162
JSON5.stringify({
164163
...settings?.fieldArguments(),
165164
nullable: Boolean(field.isNullable),
166165
}),
167166
],
167+
name: 'Field',
168168
});
169169

170170
if (isCustomsApplicable) {
@@ -176,8 +176,8 @@ export function outputType(outputType: OutputType, args: EventArguments) {
176176
true
177177
) {
178178
property.decorators.push({
179-
name: options.name,
180179
arguments: options.arguments as string[],
180+
name: options.name,
181181
});
182182
ok(options.from, "Missed 'from' part in configuration or field setting");
183183
importDeclarations.create(options);
@@ -187,8 +187,8 @@ export function outputType(outputType: OutputType, args: EventArguments) {
187187
}
188188

189189
eventEmitter.emitSync('ClassProperty', property, {
190-
location,
191190
isList,
191+
location,
192192
propertyType,
193193
});
194194
}

src/helpers/generate-file-name.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,16 @@ export function generateFileName(args: {
88
getModelName(name: string): string | undefined;
99
template: string;
1010
}) {
11-
const { template, type, name, getModelName } = args;
11+
const { getModelName, name, template, type } = args;
1212

1313
return pupa(template, {
14-
type,
1514
get model() {
1615
const result = getModelName(name) || 'prisma';
1716
return kebabCase(result);
1817
},
1918
get name() {
2019
let result = kebabCase(name);
20+
2121
for (const suffix of ['input', 'args', 'enum']) {
2222
const ending = `-${suffix}`;
2323
if (type === suffix && result.endsWith(ending)) {
@@ -31,5 +31,6 @@ export function generateFileName(args: {
3131
return pluralize(type);
3232
},
3333
},
34+
type,
3435
});
3536
}

src/helpers/get-enum-name.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
export function getEnumName(referenceName: string) {
2+
// `${Role}`
3+
return referenceName.slice(3, -2);
4+
}

src/helpers/get-graphql-import.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,12 @@ export function getGraphqlImport(args: {
1717
const {
1818
config,
1919
fileType,
20-
location,
21-
typeName,
20+
getSourceFile,
2221
isId,
22+
location,
2323
noTypeId,
2424
sourceFile,
25-
getSourceFile,
25+
typeName,
2626
} = args;
2727

2828
if (location === 'scalar') {
@@ -69,8 +69,8 @@ export function getGraphqlImport(args: {
6969
const specifier = relativePath(
7070
sourceFile.getFilePath(),
7171
getSourceFile({
72-
type: sourceFileType,
7372
name: typeName,
73+
type: sourceFileType,
7474
}).getFilePath(),
7575
);
7676

src/helpers/get-property-type.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,9 @@ export function getPropertyType(args: {
4242
return [type];
4343
}
4444
if (location === 'enumTypes') {
45-
return [`keyof typeof ${type}`];
45+
const enumType = '`${' + type + '}`';
46+
47+
return [enumType];
4648
}
4749
if (location === 'scalar') {
4850
return [type];

src/test/compatibility.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -120,22 +120,25 @@ let $prisma = new PrismaClient();
120120
by: ['id'] as UserScalarFieldEnum[],
121121
};
122122
p = x;
123-
p;
124-
x;
125123
}
126124
{
127125
let x: DummyCreateInput = { decimal: 0 as any, id: '1' };
128126
let p: Prisma.DummyCreateInput = { decimal: 0 as any, id: '2' };
129127
p = x;
130-
p;
131-
x;
132128
}
133129
{
134130
let x: DummyCreateInput['json'] = {};
135131
let p: Prisma.DummyCreateInput['json'] = {};
136132
p = x;
137133
p;
138134
}
135+
{
136+
// Will not be fixed, but can by adding id?: `${SortOrder}` | Prisma.Types.Skip
137+
// let x: UserMaxOrderByAggregateInput['id'] =
138+
// null as unknown as Prisma.UserMaxOrderByAggregateInput['id'];
139+
let p: Prisma.UserMaxOrderByAggregateInput['id'] =
140+
null as unknown as UserMaxOrderByAggregateInput['id'];
141+
}
139142
{
140143
let x: UserMaxOrderByAggregateInput = {};
141144
let p: Prisma.UserMaxOrderByAggregateInput = {};
@@ -146,14 +149,12 @@ let $prisma = new PrismaClient();
146149
{
147150
let x: UserCreateInput = {} as unknown as UserCreateInput;
148151
let p: Prisma.UserCreateInput = {} as unknown as Prisma.UserCreateInput;
149-
p = x;
150-
p;
151152
}
152153
{
153154
let x: Dummy['bytes'] = null as unknown as P.Dummy['bytes'];
154155
let p: P.Dummy['bytes'] = null as unknown as Dummy['bytes'];
155-
x;
156-
p;
156+
p = x;
157+
x = p;
157158
}
158159
{
159160
let x: Dummy = {} as unknown as Dummy;
@@ -208,7 +209,6 @@ let $prisma = new PrismaClient();
208209
console.log('result', result);
209210
});
210211
}
211-
212212
{
213213
class UserWhereUniqueInput1 extends UserWhereUniqueInput {
214214
@Field(() => String, { nullable: true })

0 commit comments

Comments
 (0)