@zenstackhq/trpc 1.0.0-beta.1 → 1.0.0-beta.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/generator.d.ts +1 -1
- package/generator.js +126 -45
- package/generator.js.map +1 -1
- package/helpers.d.ts +9 -3
- package/helpers.js +213 -22
- package/helpers.js.map +1 -1
- package/index.d.ts +2 -1
- package/index.js +2 -1
- package/index.js.map +1 -1
- package/package.json +11 -7
- package/res/client/next.ts +17 -0
- package/res/client/react.ts +17 -0
- package/res/client/utils.ts +32 -0
- package/utils/uncapitalizeFirstLetter.d.ts +0 -1
- package/utils/uncapitalizeFirstLetter.js +0 -8
- package/utils/uncapitalizeFirstLetter.js.map +0 -1
- package/zod/generator.d.ts +0 -4
- package/zod/generator.js +0 -92
- package/zod/generator.js.map +0 -1
- package/zod/index.d.ts +0 -5
- package/zod/index.js +0 -21
- package/zod/index.js.map +0 -1
- package/zod/transformer.d.ts +0 -65
- package/zod/transformer.js +0 -446
- package/zod/transformer.js.map +0 -1
- package/zod/types.d.ts +0 -20
- package/zod/types.js +0 -3
- package/zod/types.js.map +0 -1
- package/zod/utils/formatFile.d.ts +0 -1
- package/zod/utils/formatFile.js +0 -32
- package/zod/utils/formatFile.js.map +0 -1
- package/zod/utils/removeDir.d.ts +0 -1
- package/zod/utils/removeDir.js +0 -30
- package/zod/utils/removeDir.js.map +0 -1
- package/zod/utils/writeFileSafely.d.ts +0 -1
- package/zod/utils/writeFileSafely.js +0 -26
- package/zod/utils/writeFileSafely.js.map +0 -1
package/generator.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DMMF } from '@prisma/generator-helper';
|
|
1
|
+
import type { DMMF } from '@prisma/generator-helper';
|
|
2
2
|
import { PluginOptions } from '@zenstackhq/sdk';
|
|
3
3
|
import { Model } from '@zenstackhq/sdk/ast';
|
|
4
4
|
export declare function generate(model: Model, options: PluginOptions, dmmf: DMMF.Document): Promise<void>;
|
package/generator.js
CHANGED
|
@@ -25,56 +25,51 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
25
25
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
26
|
exports.generate = void 0;
|
|
27
27
|
const sdk_1 = require("@zenstackhq/sdk");
|
|
28
|
-
const fs_1 = require("fs");
|
|
28
|
+
const fs_1 = __importDefault(require("fs"));
|
|
29
29
|
const lower_case_first_1 = require("lower-case-first");
|
|
30
30
|
const path_1 = __importDefault(require("path"));
|
|
31
|
+
const ts_morph_1 = require("ts-morph");
|
|
32
|
+
const upper_case_first_1 = require("upper-case-first");
|
|
31
33
|
const _1 = require(".");
|
|
32
34
|
const helpers_1 = require("./helpers");
|
|
33
35
|
const project_1 = require("./project");
|
|
34
36
|
const removeDir_1 = __importDefault(require("./utils/removeDir"));
|
|
35
|
-
const generator_1 = require("./zod/generator");
|
|
36
37
|
function generate(model, options, dmmf) {
|
|
38
|
+
var _a;
|
|
37
39
|
return __awaiter(this, void 0, void 0, function* () {
|
|
38
40
|
let outDir = (0, sdk_1.requireOption)(options, 'output');
|
|
39
41
|
outDir = (0, sdk_1.resolvePath)(outDir, options);
|
|
40
42
|
// resolve "generateModelActions" option
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
}
|
|
50
|
-
else if (Array.isArray(options.generateModelActions) &&
|
|
51
|
-
options.generateModelActions.every((i) => typeof i === 'string')) {
|
|
52
|
-
// string array
|
|
53
|
-
generateModelActions = options.generateModelActions;
|
|
54
|
-
}
|
|
55
|
-
else {
|
|
56
|
-
throw new sdk_1.PluginError(_1.name, `Invalid "generateModelActions" option: must be a comma-separated string or an array of strings`);
|
|
57
|
-
}
|
|
43
|
+
const generateModelActions = parseOptionAsStrings(options, 'generateModelActions');
|
|
44
|
+
// resolve "generateClientHelpers" option
|
|
45
|
+
const generateClientHelpers = parseOptionAsStrings(options, 'generateClientHelpers');
|
|
46
|
+
if (generateClientHelpers && !generateClientHelpers.every((v) => ['react', 'next'].includes(v))) {
|
|
47
|
+
throw new sdk_1.PluginError(_1.name, `Option "generateClientHelpers" only support values "react" and "next"`);
|
|
48
|
+
}
|
|
49
|
+
if (options.zodSchemasImport && typeof options.zodSchemasImport !== 'string') {
|
|
50
|
+
throw new sdk_1.PluginError(_1.name, `Option "zodSchemasImport" must be a string`);
|
|
58
51
|
}
|
|
59
|
-
yield fs_1.promises.mkdir(outDir, { recursive: true });
|
|
52
|
+
yield fs_1.default.promises.mkdir(outDir, { recursive: true });
|
|
60
53
|
yield (0, removeDir_1.default)(outDir, true);
|
|
61
|
-
yield (0, generator_1.generate)(model, options, dmmf);
|
|
62
54
|
const prismaClientDmmf = dmmf;
|
|
63
55
|
const modelOperations = prismaClientDmmf.mappings.modelOperations;
|
|
64
56
|
const models = prismaClientDmmf.datamodel.models;
|
|
65
57
|
const hiddenModels = [];
|
|
66
58
|
(0, helpers_1.resolveModelsComments)(models, hiddenModels);
|
|
67
|
-
|
|
59
|
+
const zodSchemasImport = (_a = options.zodSchemasImport) !== null && _a !== void 0 ? _a : '@zenstackhq/runtime/zod';
|
|
60
|
+
createAppRouter(outDir, modelOperations, hiddenModels, generateModelActions, generateClientHelpers, model, zodSchemasImport);
|
|
68
61
|
createHelper(outDir);
|
|
69
62
|
yield (0, sdk_1.saveProject)(project_1.project);
|
|
70
63
|
});
|
|
71
64
|
}
|
|
72
65
|
exports.generate = generate;
|
|
73
|
-
function createAppRouter(outDir, modelOperations, hiddenModels, generateModelActions) {
|
|
74
|
-
const
|
|
66
|
+
function createAppRouter(outDir, modelOperations, hiddenModels, generateModelActions, generateClientHelpers, zmodel, zodSchemasImport) {
|
|
67
|
+
const indexFile = path_1.default.resolve(outDir, 'routers', `index.ts`);
|
|
68
|
+
const appRouter = project_1.project.createSourceFile(indexFile, undefined, {
|
|
75
69
|
overwrite: true,
|
|
76
70
|
});
|
|
77
71
|
appRouter.addStatements('/* eslint-disable */');
|
|
72
|
+
const prismaImport = (0, sdk_1.getPrismaClientImportSpec)(zmodel, path_1.default.dirname(indexFile));
|
|
78
73
|
appRouter.addImportDeclarations([
|
|
79
74
|
{
|
|
80
75
|
namedImports: ['AnyRootConfig'],
|
|
@@ -82,10 +77,10 @@ function createAppRouter(outDir, modelOperations, hiddenModels, generateModelAct
|
|
|
82
77
|
},
|
|
83
78
|
{
|
|
84
79
|
namedImports: ['PrismaClient'],
|
|
85
|
-
moduleSpecifier:
|
|
80
|
+
moduleSpecifier: prismaImport,
|
|
86
81
|
},
|
|
87
82
|
{
|
|
88
|
-
namedImports: ['createRouterFactory'],
|
|
83
|
+
namedImports: ['createRouterFactory', 'AnyRouter'],
|
|
89
84
|
moduleSpecifier: '@trpc/server/dist/core/router',
|
|
90
85
|
},
|
|
91
86
|
{
|
|
@@ -112,23 +107,22 @@ function createAppRouter(outDir, modelOperations, hiddenModels, generateModelAct
|
|
|
112
107
|
}
|
|
113
108
|
|
|
114
109
|
`);
|
|
115
|
-
const
|
|
110
|
+
const filteredModelOperations = modelOperations.filter((mo) => !hiddenModels.includes(mo.model));
|
|
111
|
+
appRouter
|
|
112
|
+
.addFunction({
|
|
116
113
|
name: 'createRouter<Config extends BaseConfig>',
|
|
117
114
|
parameters: [
|
|
118
115
|
{ name: 'router', type: 'RouterFactory<Config>' },
|
|
119
116
|
{ name: 'procedure', type: 'ProcBuilder<Config>' },
|
|
120
117
|
],
|
|
121
118
|
isExported: true,
|
|
122
|
-
})
|
|
123
|
-
|
|
119
|
+
})
|
|
120
|
+
.setBodyText((writer) => {
|
|
124
121
|
writer.write('return router(');
|
|
125
122
|
writer.block(() => {
|
|
126
|
-
for (const modelOperation of
|
|
123
|
+
for (const modelOperation of filteredModelOperations) {
|
|
127
124
|
const { model } = modelOperation, operations = __rest(modelOperation, ["model"]);
|
|
128
|
-
|
|
129
|
-
continue;
|
|
130
|
-
}
|
|
131
|
-
generateModelCreateRouter(project_1.project, model, operations, outDir, generateModelActions);
|
|
125
|
+
generateModelCreateRouter(project_1.project, model, operations, outDir, generateModelActions, generateClientHelpers, zmodel, zodSchemasImport);
|
|
132
126
|
appRouter.addImportDeclaration({
|
|
133
127
|
defaultImport: `create${model}Router`,
|
|
134
128
|
moduleSpecifier: `./${model}.router`,
|
|
@@ -138,9 +132,49 @@ function createAppRouter(outDir, modelOperations, hiddenModels, generateModelAct
|
|
|
138
132
|
});
|
|
139
133
|
writer.write(');');
|
|
140
134
|
});
|
|
135
|
+
if (generateClientHelpers) {
|
|
136
|
+
appRouter.addInterface({
|
|
137
|
+
name: 'ClientType',
|
|
138
|
+
typeParameters: ['AppRouter extends AnyRouter'],
|
|
139
|
+
isExported: true,
|
|
140
|
+
properties: filteredModelOperations.map(({ model }) => {
|
|
141
|
+
appRouter.addImportDeclaration({
|
|
142
|
+
namedImports: [{ name: 'ClientType', alias: `${(0, upper_case_first_1.upperCaseFirst)(model)}ClientType` }],
|
|
143
|
+
moduleSpecifier: `./${model}.router`,
|
|
144
|
+
});
|
|
145
|
+
return {
|
|
146
|
+
name: (0, lower_case_first_1.lowerCaseFirst)(model),
|
|
147
|
+
type: `${(0, upper_case_first_1.upperCaseFirst)(model)}ClientType<AppRouter>`,
|
|
148
|
+
};
|
|
149
|
+
}),
|
|
150
|
+
});
|
|
151
|
+
createClientHelpers(outDir, generateClientHelpers);
|
|
152
|
+
}
|
|
141
153
|
appRouter.formatText();
|
|
142
154
|
}
|
|
143
|
-
function
|
|
155
|
+
function createClientHelpers(outputDir, generateClientHelpers) {
|
|
156
|
+
const utils = project_1.project.createSourceFile(path_1.default.resolve(outputDir, 'client', `utils.ts`), undefined, {
|
|
157
|
+
overwrite: true,
|
|
158
|
+
});
|
|
159
|
+
utils.replaceWithText(fs_1.default.readFileSync(path_1.default.join(__dirname, './res/client/utils.ts'), 'utf-8'));
|
|
160
|
+
for (const client of generateClientHelpers) {
|
|
161
|
+
switch (client) {
|
|
162
|
+
case 'react': {
|
|
163
|
+
const content = fs_1.default.readFileSync(path_1.default.join(__dirname, './res/client/react.ts'), 'utf-8');
|
|
164
|
+
project_1.project.createSourceFile(path_1.default.resolve(outputDir, 'client', 'react.ts'), content, {
|
|
165
|
+
overwrite: true,
|
|
166
|
+
});
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
case 'next': {
|
|
170
|
+
const content = fs_1.default.readFileSync(path_1.default.join(__dirname, './res/client/next.ts'), 'utf-8');
|
|
171
|
+
project_1.project.createSourceFile(path_1.default.resolve(outputDir, 'client', 'next.ts'), content, { overwrite: true });
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
function generateModelCreateRouter(project, model, operations, outputDir, generateModelActions, generateClientHelpers, zmodel, zodSchemasImport) {
|
|
144
178
|
const modelRouter = project.createSourceFile(path_1.default.resolve(outputDir, 'routers', `${model}.router.ts`), undefined, {
|
|
145
179
|
overwrite: true,
|
|
146
180
|
});
|
|
@@ -151,10 +185,12 @@ function generateModelCreateRouter(project, model, operations, outputDir, genera
|
|
|
151
185
|
moduleSpecifier: '.',
|
|
152
186
|
},
|
|
153
187
|
]);
|
|
154
|
-
(0, helpers_1.generateRouterSchemaImports)(modelRouter, model);
|
|
188
|
+
(0, helpers_1.generateRouterSchemaImports)(modelRouter, model, zodSchemasImport);
|
|
155
189
|
(0, helpers_1.generateHelperImport)(modelRouter);
|
|
156
|
-
|
|
157
|
-
.
|
|
190
|
+
if (generateClientHelpers) {
|
|
191
|
+
(0, helpers_1.generateRouterTypingImports)(modelRouter, zmodel);
|
|
192
|
+
}
|
|
193
|
+
const createRouterFunc = modelRouter.addFunction({
|
|
158
194
|
name: 'createRouter<Config extends BaseConfig>',
|
|
159
195
|
parameters: [
|
|
160
196
|
{ name: 'router', type: 'RouterFactory<Config>' },
|
|
@@ -162,23 +198,48 @@ function generateModelCreateRouter(project, model, operations, outputDir, genera
|
|
|
162
198
|
],
|
|
163
199
|
isExported: true,
|
|
164
200
|
isDefaultExport: true,
|
|
165
|
-
})
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
201
|
+
});
|
|
202
|
+
let routerTypingStructure = undefined;
|
|
203
|
+
if (generateClientHelpers) {
|
|
204
|
+
// generate an interface for precise Prisma-like typing for the router procedures
|
|
205
|
+
// which will be used to correct tRPC's typing on the client side
|
|
206
|
+
routerTypingStructure = {
|
|
207
|
+
kind: ts_morph_1.StructureKind.Interface,
|
|
208
|
+
name: 'ClientType',
|
|
209
|
+
isExported: true,
|
|
210
|
+
typeParameters: ['AppRouter extends AnyRouter', `Context = AppRouter['_def']['_config']['$types']['ctx']`],
|
|
211
|
+
properties: [],
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
createRouterFunc.setBodyText((funcWriter) => {
|
|
215
|
+
funcWriter.write('return router(');
|
|
216
|
+
funcWriter.block(() => {
|
|
217
|
+
var _a;
|
|
169
218
|
for (const [opType, opNameWithModel] of Object.entries(operations)) {
|
|
170
219
|
const baseOpType = opType.replace('OrThrow', '');
|
|
171
|
-
const inputType = (0, helpers_1.
|
|
220
|
+
const inputType = (0, helpers_1.getInputSchemaByOpName)(baseOpType, model);
|
|
172
221
|
const generateOpName = opType.replace(/One$/, '');
|
|
173
222
|
if (opNameWithModel &&
|
|
174
223
|
inputType &&
|
|
175
224
|
(!generateModelActions || generateModelActions.includes(generateOpName))) {
|
|
176
|
-
(0, helpers_1.generateProcedure)(
|
|
225
|
+
(0, helpers_1.generateProcedure)(funcWriter, generateOpName, inputType, model, baseOpType);
|
|
226
|
+
if (routerTypingStructure) {
|
|
227
|
+
(_a = routerTypingStructure.properties) === null || _a === void 0 ? void 0 : _a.push({
|
|
228
|
+
kind: ts_morph_1.StructureKind.PropertySignature,
|
|
229
|
+
name: generateOpName,
|
|
230
|
+
type: (writer) => {
|
|
231
|
+
(0, helpers_1.generateRouterTyping)(writer, generateOpName, model, baseOpType);
|
|
232
|
+
},
|
|
233
|
+
});
|
|
234
|
+
}
|
|
177
235
|
}
|
|
178
236
|
}
|
|
179
237
|
});
|
|
180
|
-
|
|
238
|
+
funcWriter.write(');');
|
|
181
239
|
});
|
|
240
|
+
if (routerTypingStructure) {
|
|
241
|
+
modelRouter.addInterface(routerTypingStructure);
|
|
242
|
+
}
|
|
182
243
|
modelRouter.formatText();
|
|
183
244
|
}
|
|
184
245
|
function createHelper(outDir) {
|
|
@@ -276,4 +337,24 @@ function createHelper(outDir) {
|
|
|
276
337
|
`);
|
|
277
338
|
checkRead.formatText();
|
|
278
339
|
}
|
|
340
|
+
function parseOptionAsStrings(options, optionaName) {
|
|
341
|
+
const value = options[optionaName];
|
|
342
|
+
if (value === undefined) {
|
|
343
|
+
return undefined;
|
|
344
|
+
}
|
|
345
|
+
else if (typeof value === 'string') {
|
|
346
|
+
// comma separated string
|
|
347
|
+
return value
|
|
348
|
+
.split(',')
|
|
349
|
+
.filter((i) => !!i)
|
|
350
|
+
.map((i) => i.trim());
|
|
351
|
+
}
|
|
352
|
+
else if (Array.isArray(value) && value.every((i) => typeof i === 'string')) {
|
|
353
|
+
// string array
|
|
354
|
+
return value;
|
|
355
|
+
}
|
|
356
|
+
else {
|
|
357
|
+
throw new sdk_1.PluginError(_1.name, `Invalid "${optionaName}" option: must be a comma-separated string or an array of strings`);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
279
360
|
//# sourceMappingURL=generator.js.map
|
package/generator.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generator.js","sourceRoot":"","sources":["../src/generator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,
|
|
1
|
+
{"version":3,"file":"generator.js","sourceRoot":"","sources":["../src/generator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,yCASyB;AAEzB,4CAAoB;AACpB,uDAAkD;AAClD,gDAAwB;AACxB,uCAA6G;AAC7G,uDAAkD;AAClD,wBAAyB;AACzB,uC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AC"}
|
package/helpers.d.ts
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
|
-
import { DMMF } from '@prisma/generator-helper';
|
|
1
|
+
import type { DMMF } from '@prisma/generator-helper';
|
|
2
|
+
import { Model } from '@zenstackhq/sdk/ast';
|
|
2
3
|
import { CodeBlockWriter, SourceFile } from 'ts-morph';
|
|
3
4
|
export declare function generateProcedure(writer: CodeBlockWriter, opType: string, typeName: string, modelName: string, baseOpType: string): void;
|
|
4
|
-
|
|
5
|
+
/**
|
|
6
|
+
* Generate precise Prisma-like typing for router procedures.
|
|
7
|
+
*/
|
|
8
|
+
export declare function generateRouterTyping(writer: CodeBlockWriter, opType: string, modelName: string, baseOpType: string): void;
|
|
9
|
+
export declare function generateRouterTypingImports(sourceFile: SourceFile, model: Model): void;
|
|
10
|
+
export declare function generateRouterSchemaImports(sourceFile: SourceFile, name: string, zodSchemasImport: string): void;
|
|
5
11
|
export declare function generateHelperImport(sourceFile: SourceFile): void;
|
|
6
|
-
export declare const
|
|
12
|
+
export declare const getInputSchemaByOpName: (opName: string, modelName: string) => string | undefined;
|
|
7
13
|
export declare const getProcedureTypeByOpName: (opName: string) => string | undefined;
|
|
8
14
|
export declare function resolveModelsComments(models: DMMF.Model[], hiddenModels: string[]): void;
|
package/helpers.js
CHANGED
|
@@ -1,81 +1,272 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.resolveModelsComments = exports.getProcedureTypeByOpName = exports.
|
|
4
|
-
const
|
|
3
|
+
exports.resolveModelsComments = exports.getProcedureTypeByOpName = exports.getInputSchemaByOpName = exports.generateHelperImport = exports.generateRouterSchemaImports = exports.generateRouterTypingImports = exports.generateRouterTyping = exports.generateProcedure = void 0;
|
|
4
|
+
const sdk_1 = require("@zenstackhq/sdk");
|
|
5
|
+
const lower_case_first_1 = require("lower-case-first");
|
|
6
|
+
const upper_case_first_1 = require("upper-case-first");
|
|
7
|
+
const _1 = require(".");
|
|
5
8
|
function generateProcedure(writer, opType, typeName, modelName, baseOpType) {
|
|
6
9
|
const procType = (0, exports.getProcedureTypeByOpName)(baseOpType);
|
|
7
10
|
const prismaMethod = opType.replace('One', '');
|
|
8
11
|
if (procType === 'query') {
|
|
12
|
+
// the cast "as any" is to circumvent a TS compiler misfired error in certain cases
|
|
9
13
|
writer.write(`
|
|
10
|
-
${opType}: procedure.input(${typeName}).query(({ctx, input}) => checkRead(db(ctx).${(0,
|
|
14
|
+
${opType}: procedure.input(${typeName}).query(({ctx, input}) => checkRead(db(ctx).${(0, lower_case_first_1.lowerCaseFirst)(modelName)}.${prismaMethod}(input as any))),
|
|
11
15
|
`);
|
|
12
16
|
}
|
|
13
17
|
else if (procType === 'mutation') {
|
|
18
|
+
// the cast "as any" is to circumvent a TS compiler misfired error in certain cases
|
|
14
19
|
writer.write(`
|
|
15
|
-
${opType}: procedure.input(${typeName}).mutation(async ({ctx, input}) => checkMutate(db(ctx).${(0,
|
|
20
|
+
${opType}: procedure.input(${typeName}).mutation(async ({ctx, input}) => checkMutate(db(ctx).${(0, lower_case_first_1.lowerCaseFirst)(modelName)}.${prismaMethod}(input as any))),
|
|
16
21
|
`);
|
|
17
22
|
}
|
|
18
23
|
}
|
|
19
24
|
exports.generateProcedure = generateProcedure;
|
|
20
|
-
|
|
21
|
-
|
|
25
|
+
/**
|
|
26
|
+
* Given a model and Prisma operation, returns related TS types.
|
|
27
|
+
*/
|
|
28
|
+
function getPrismaOperationTypes(model, operation) {
|
|
29
|
+
// TODO: find a way to derive from Prisma Client API's generic types
|
|
30
|
+
// instead of duplicating them
|
|
31
|
+
const capModel = (0, upper_case_first_1.upperCaseFirst)(model);
|
|
32
|
+
const capOperation = (0, upper_case_first_1.upperCaseFirst)(operation);
|
|
33
|
+
let genericBase = `Prisma.${capModel}${capOperation}Args`;
|
|
34
|
+
const getPayload = `Prisma.${capModel}GetPayload<T>`;
|
|
35
|
+
const selectSubset = `Prisma.SelectSubset<T, ${genericBase}>`;
|
|
36
|
+
let argsType;
|
|
37
|
+
let resultType;
|
|
38
|
+
switch (operation) {
|
|
39
|
+
case 'findUnique':
|
|
40
|
+
case 'findUniqueOrThrow':
|
|
41
|
+
case 'findFirst':
|
|
42
|
+
case 'findFirstOrThrow':
|
|
43
|
+
argsType = selectSubset;
|
|
44
|
+
resultType = getPayload;
|
|
45
|
+
break;
|
|
46
|
+
case 'findMany':
|
|
47
|
+
argsType = selectSubset;
|
|
48
|
+
resultType = `Array<${getPayload}>`;
|
|
49
|
+
break;
|
|
50
|
+
case 'create':
|
|
51
|
+
argsType = selectSubset;
|
|
52
|
+
resultType = getPayload;
|
|
53
|
+
break;
|
|
54
|
+
case 'createMany':
|
|
55
|
+
argsType = selectSubset;
|
|
56
|
+
resultType = `Prisma.BatchPayload`;
|
|
57
|
+
break;
|
|
58
|
+
case 'update':
|
|
59
|
+
argsType = selectSubset;
|
|
60
|
+
resultType = getPayload;
|
|
61
|
+
break;
|
|
62
|
+
case 'updateMany':
|
|
63
|
+
argsType = selectSubset;
|
|
64
|
+
resultType = `Prisma.BatchPayload`;
|
|
65
|
+
break;
|
|
66
|
+
case 'upsert':
|
|
67
|
+
argsType = selectSubset;
|
|
68
|
+
resultType = getPayload;
|
|
69
|
+
break;
|
|
70
|
+
case 'delete':
|
|
71
|
+
argsType = selectSubset;
|
|
72
|
+
resultType = getPayload;
|
|
73
|
+
break;
|
|
74
|
+
case 'deleteMany':
|
|
75
|
+
argsType = selectSubset;
|
|
76
|
+
resultType = `Prisma.BatchPayload`;
|
|
77
|
+
break;
|
|
78
|
+
case 'count':
|
|
79
|
+
argsType = `Prisma.Subset<T, ${genericBase}>`;
|
|
80
|
+
resultType = `'select' extends keyof T'
|
|
81
|
+
? T['select'] extends true
|
|
82
|
+
? number
|
|
83
|
+
: GetScalarType<T['select'], ${capModel}CountAggregateOutputType>
|
|
84
|
+
: number`;
|
|
85
|
+
break;
|
|
86
|
+
case 'aggregate':
|
|
87
|
+
argsType = `Prisma.Subset<T, ${genericBase}>`;
|
|
88
|
+
resultType = `Prisma.Get${capModel}AggregateType<T>`;
|
|
89
|
+
break;
|
|
90
|
+
case 'groupBy':
|
|
91
|
+
genericBase = `Prisma.${capModel}GroupByArgs,
|
|
92
|
+
HasSelectOrTake extends Prisma.Or<
|
|
93
|
+
Prisma.Extends<'skip', Prisma.Keys<T>>,
|
|
94
|
+
Prisma.Extends<'take', Prisma.Keys<T>>
|
|
95
|
+
>,
|
|
96
|
+
OrderByArg extends Prisma.True extends HasSelectOrTake
|
|
97
|
+
? { orderBy: Prisma.${capModel}GroupByArgs['orderBy'] }
|
|
98
|
+
: { orderBy?: Prisma.${capModel}GroupByArgs['orderBy'] },
|
|
99
|
+
OrderFields extends Prisma.ExcludeUnderscoreKeys<Prisma.Keys<Prisma.MaybeTupleToUnion<T['orderBy']>>>,
|
|
100
|
+
ByFields extends Prisma.MaybeTupleToUnion<T['by']>,
|
|
101
|
+
ByValid extends Prisma.Has<ByFields, OrderFields>,
|
|
102
|
+
HavingFields extends Prisma.GetHavingFields<T['having']>,
|
|
103
|
+
HavingValid extends Prisma.Has<ByFields, HavingFields>,
|
|
104
|
+
ByEmpty extends T['by'] extends never[] ? Prisma.True : Prisma.False,
|
|
105
|
+
InputErrors extends ByEmpty extends Prisma.True
|
|
106
|
+
? \`Error: "by" must not be empty.\`
|
|
107
|
+
: HavingValid extends Prisma.False
|
|
108
|
+
? {
|
|
109
|
+
[P in HavingFields]: P extends ByFields
|
|
110
|
+
? never
|
|
111
|
+
: P extends string
|
|
112
|
+
? \`Error: Field "\${P}" used in "having" needs to be provided in "by".\`
|
|
113
|
+
: [
|
|
114
|
+
Error,
|
|
115
|
+
'Field ',
|
|
116
|
+
P,
|
|
117
|
+
\` in "having" needs to be provided in "by"\`,
|
|
118
|
+
]
|
|
119
|
+
}[HavingFields]
|
|
120
|
+
: 'take' extends Prisma.Keys<T>
|
|
121
|
+
? 'orderBy' extends Prisma.Keys<T>
|
|
122
|
+
? ByValid extends Prisma.True
|
|
123
|
+
? {}
|
|
124
|
+
: {
|
|
125
|
+
[P in OrderFields]: P extends ByFields
|
|
126
|
+
? never
|
|
127
|
+
: \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\`
|
|
128
|
+
}[OrderFields]
|
|
129
|
+
: 'Error: If you provide "take", you also need to provide "orderBy"'
|
|
130
|
+
: 'skip' extends Prisma.Keys<T>
|
|
131
|
+
? 'orderBy' extends Prisma.Keys<T>
|
|
132
|
+
? ByValid extends Prisma.True
|
|
133
|
+
? {}
|
|
134
|
+
: {
|
|
135
|
+
[P in OrderFields]: P extends ByFields
|
|
136
|
+
? never
|
|
137
|
+
: \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\`
|
|
138
|
+
}[OrderFields]
|
|
139
|
+
: 'Error: If you provide "skip", you also need to provide "orderBy"'
|
|
140
|
+
: ByValid extends Prisma.True
|
|
141
|
+
? {}
|
|
142
|
+
: {
|
|
143
|
+
[P in OrderFields]: P extends ByFields
|
|
144
|
+
? never
|
|
145
|
+
: \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\`
|
|
146
|
+
}[OrderFields]
|
|
147
|
+
`;
|
|
148
|
+
argsType = `Prisma.SubsetIntersection<T, Prisma.${capModel}GroupByArgs, OrderByArg> & InputErrors`;
|
|
149
|
+
resultType = `{} extends InputErrors ? Prisma.Get${capModel}GroupByPayload<T> : InputErrors`;
|
|
150
|
+
break;
|
|
151
|
+
default:
|
|
152
|
+
throw new sdk_1.PluginError(_1.name, `Unsupported operation: "${operation}"`);
|
|
153
|
+
}
|
|
154
|
+
return { genericBase, argsType, resultType };
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Generate precise Prisma-like typing for router procedures.
|
|
158
|
+
*/
|
|
159
|
+
function generateRouterTyping(writer, opType, modelName, baseOpType) {
|
|
160
|
+
const procType = (0, exports.getProcedureTypeByOpName)(baseOpType);
|
|
161
|
+
const { genericBase, argsType, resultType } = getPrismaOperationTypes(modelName, opType);
|
|
162
|
+
const errorType = `TRPCClientErrorLike<AppRouter>`;
|
|
163
|
+
writer.block(() => {
|
|
164
|
+
if (procType === 'query') {
|
|
165
|
+
writer.writeLine(`
|
|
166
|
+
useQuery: <T extends ${genericBase}>(
|
|
167
|
+
input: ${argsType},
|
|
168
|
+
opts?: UseTRPCQueryOptions<string, T, ${resultType}, ${resultType}, Error>
|
|
169
|
+
) => UseTRPCQueryResult<
|
|
170
|
+
${resultType},
|
|
171
|
+
${errorType}
|
|
172
|
+
>;
|
|
173
|
+
useInfiniteQuery: <T extends ${genericBase}>(
|
|
174
|
+
input: Omit<${argsType}, 'cursor'>,
|
|
175
|
+
opts?: UseTRPCInfiniteQueryOptions<string, T, ${resultType}, Error>
|
|
176
|
+
) => UseTRPCInfiniteQueryResult<
|
|
177
|
+
${resultType},
|
|
178
|
+
${errorType}
|
|
179
|
+
>;
|
|
180
|
+
`);
|
|
181
|
+
}
|
|
182
|
+
else if (procType === 'mutation') {
|
|
183
|
+
writer.writeLine(`
|
|
184
|
+
useMutation: <T extends ${genericBase}>(opts?: UseTRPCMutationOptions<
|
|
185
|
+
${genericBase},
|
|
186
|
+
${errorType},
|
|
187
|
+
Prisma.${(0, upper_case_first_1.upperCaseFirst)(modelName)}GetPayload<null>,
|
|
188
|
+
Context
|
|
189
|
+
>,) =>
|
|
190
|
+
Omit<UseTRPCMutationResult<${resultType}, ${errorType}, ${argsType}, Context>, 'mutateAsync'> & {
|
|
191
|
+
mutateAsync:
|
|
192
|
+
<T extends ${genericBase}>(variables: T, opts?: UseTRPCMutationOptions<T, ${errorType}, ${resultType}, Context>) => Promise<${resultType}>
|
|
193
|
+
};
|
|
194
|
+
`);
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
exports.generateRouterTyping = generateRouterTyping;
|
|
199
|
+
function generateRouterTypingImports(sourceFile, model) {
|
|
200
|
+
const importingDir = sourceFile.getDirectoryPath();
|
|
201
|
+
const prismaImport = (0, sdk_1.getPrismaClientImportSpec)(model, importingDir);
|
|
202
|
+
sourceFile.addStatements([
|
|
203
|
+
`import type { Prisma } from '${prismaImport}';`,
|
|
204
|
+
`import type { UseTRPCMutationOptions, UseTRPCMutationResult, UseTRPCQueryOptions, UseTRPCQueryResult, UseTRPCInfiniteQueryOptions, UseTRPCInfiniteQueryResult } from '@trpc/react-query/shared';`,
|
|
205
|
+
`import type { TRPCClientErrorLike } from '@trpc/client';`,
|
|
206
|
+
`import type { AnyRouter } from '@trpc/server';`,
|
|
207
|
+
]);
|
|
208
|
+
}
|
|
209
|
+
exports.generateRouterTypingImports = generateRouterTypingImports;
|
|
210
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
211
|
+
function generateRouterSchemaImports(sourceFile, name, zodSchemasImport) {
|
|
212
|
+
sourceFile.addStatements(`import { ${name}InputSchema } from '${zodSchemasImport}/input';`);
|
|
22
213
|
}
|
|
23
214
|
exports.generateRouterSchemaImports = generateRouterSchemaImports;
|
|
24
215
|
function generateHelperImport(sourceFile) {
|
|
25
216
|
sourceFile.addStatements(`import { checkRead, checkMutate } from '../helper';`);
|
|
26
217
|
}
|
|
27
218
|
exports.generateHelperImport = generateHelperImport;
|
|
28
|
-
const
|
|
219
|
+
const getInputSchemaByOpName = (opName, modelName) => {
|
|
29
220
|
let inputType;
|
|
30
221
|
switch (opName) {
|
|
31
222
|
case 'findUnique':
|
|
32
|
-
inputType = `${modelName}
|
|
223
|
+
inputType = `${modelName}InputSchema.findUnique`;
|
|
33
224
|
break;
|
|
34
225
|
case 'findFirst':
|
|
35
|
-
inputType = `${modelName}
|
|
226
|
+
inputType = `${modelName}InputSchema.findFirst`;
|
|
36
227
|
break;
|
|
37
228
|
case 'findMany':
|
|
38
|
-
inputType = `${modelName}
|
|
229
|
+
inputType = `${modelName}InputSchema.findMany`;
|
|
39
230
|
break;
|
|
40
231
|
case 'findRaw':
|
|
41
|
-
inputType = `${modelName}
|
|
232
|
+
inputType = `${modelName}InputSchema.findRawObject`;
|
|
42
233
|
break;
|
|
43
234
|
case 'createOne':
|
|
44
|
-
inputType = `${modelName}
|
|
235
|
+
inputType = `${modelName}InputSchema.create`;
|
|
45
236
|
break;
|
|
46
237
|
case 'createMany':
|
|
47
|
-
inputType = `${modelName}
|
|
238
|
+
inputType = `${modelName}InputSchema.createMany`;
|
|
48
239
|
break;
|
|
49
240
|
case 'deleteOne':
|
|
50
|
-
inputType = `${modelName}
|
|
241
|
+
inputType = `${modelName}InputSchema.delete`;
|
|
51
242
|
break;
|
|
52
243
|
case 'updateOne':
|
|
53
|
-
inputType = `${modelName}
|
|
244
|
+
inputType = `${modelName}InputSchema.update`;
|
|
54
245
|
break;
|
|
55
246
|
case 'deleteMany':
|
|
56
|
-
inputType = `${modelName}
|
|
247
|
+
inputType = `${modelName}InputSchema.deleteMany`;
|
|
57
248
|
break;
|
|
58
249
|
case 'updateMany':
|
|
59
|
-
inputType = `${modelName}
|
|
250
|
+
inputType = `${modelName}InputSchema.updateMany`;
|
|
60
251
|
break;
|
|
61
252
|
case 'upsertOne':
|
|
62
|
-
inputType = `${modelName}
|
|
253
|
+
inputType = `${modelName}InputSchema.upsert`;
|
|
63
254
|
break;
|
|
64
255
|
case 'aggregate':
|
|
65
|
-
inputType = `${modelName}
|
|
256
|
+
inputType = `${modelName}InputSchema.aggregate`;
|
|
66
257
|
break;
|
|
67
258
|
case 'aggregateRaw':
|
|
68
|
-
inputType = `${modelName}
|
|
259
|
+
inputType = `${modelName}InputSchema.aggregateRawObject`;
|
|
69
260
|
break;
|
|
70
261
|
case 'groupBy':
|
|
71
|
-
inputType = `${modelName}
|
|
262
|
+
inputType = `${modelName}InputSchema.groupBy`;
|
|
72
263
|
break;
|
|
73
264
|
default:
|
|
74
265
|
console.log('getInputTypeByOpName: ', { opName, modelName });
|
|
75
266
|
}
|
|
76
267
|
return inputType;
|
|
77
268
|
};
|
|
78
|
-
exports.
|
|
269
|
+
exports.getInputSchemaByOpName = getInputSchemaByOpName;
|
|
79
270
|
const getProcedureTypeByOpName = (opName) => {
|
|
80
271
|
let procType;
|
|
81
272
|
switch (opName) {
|