@zenstackhq/server 1.0.0-alpha.100

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 ZenStack
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # ZenStack Fastify Plugin Library
2
+
3
+ This package provides a Fastify plugin for ZenStack.
4
+
5
+ Visit [Homepage](https://zenstack.dev) for more details.
@@ -0,0 +1 @@
1
+ export { default as ZenStackMiddleware } from './middleware';
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ZenStackMiddleware = void 0;
7
+ var middleware_1 = require("./middleware");
8
+ Object.defineProperty(exports, "ZenStackMiddleware", { enumerable: true, get: function () { return __importDefault(middleware_1).default; } });
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/express/index.ts"],"names":[],"mappings":";;;;;;AAAA,2CAA6D;AAApD,iIAAA,OAAO,OAAsB"}
@@ -0,0 +1,26 @@
1
+ import { ModelZodSchema } from '@zenstackhq/runtime/zod';
2
+ import type { Handler, Request, Response } from 'express';
3
+ import { LoggerConfig } from '../openapi';
4
+ /**
5
+ * Express middleware options
6
+ */
7
+ export interface MiddlewareOptions {
8
+ /**
9
+ * Callback for getting a PrismaClient for the given request
10
+ */
11
+ getPrisma: (req: Request, res: Response) => unknown | Promise<unknown>;
12
+ /**
13
+ * Logger settings
14
+ */
15
+ logger?: LoggerConfig;
16
+ /**
17
+ * Zod schemas for validating request input. Pass `true` to load from standard location
18
+ * (need to enable `@core/zod` plugin in schema.zmodel) or omit to disable input validation.
19
+ */
20
+ zodSchemas?: ModelZodSchema | boolean;
21
+ }
22
+ /**
23
+ * Creates an Express middleware for handling CRUD requests.
24
+ */
25
+ declare const factory: (options: MiddlewareOptions) => Handler;
26
+ export default factory;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const zod_1 = require("@zenstackhq/runtime/zod");
13
+ const openapi_1 = require("../openapi");
14
+ /**
15
+ * Creates an Express middleware for handling CRUD requests.
16
+ */
17
+ const factory = (options) => {
18
+ let schemas;
19
+ if (typeof options.zodSchemas === 'object') {
20
+ schemas = options.zodSchemas;
21
+ }
22
+ else if (options.zodSchemas === true) {
23
+ schemas = (0, zod_1.getModelZodSchemas)();
24
+ }
25
+ return (request, response) => __awaiter(void 0, void 0, void 0, function* () {
26
+ const prisma = (yield options.getPrisma(request, response));
27
+ if (!prisma) {
28
+ throw new Error('unable to get prisma from request context');
29
+ }
30
+ const r = yield (0, openapi_1.handleRequest)({
31
+ method: request.method,
32
+ path: request.path,
33
+ query: request.query,
34
+ requestBody: request.body,
35
+ prisma,
36
+ logger: options.logger,
37
+ zodSchemas: schemas,
38
+ });
39
+ response.status(r.status).json(r.body);
40
+ });
41
+ };
42
+ exports.default = factory;
43
+ //# sourceMappingURL=middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../src/express/middleware.ts"],"names":[],"mappings":";;;;;;;;;;;AAEA,iDAA6E;AAE7E,wCAAyD;AAuBzD;;GAEG;AACH,MAAM,OAAO,GAAG,CAAC,OAA0B,EAAW,EAAE;IACpD,IAAI,OAAmC,CAAC;IACxC,IAAI,OAAO,OAAO,CAAC,UAAU,KAAK,QAAQ,EAAE;QACxC,OAAO,GAAG,OAAO,CAAC,UAAU,CAAC;KAChC;SAAM,IAAI,OAAO,CAAC,UAAU,KAAK,IAAI,EAAE;QACpC,OAAO,GAAG,IAAA,wBAAkB,GAAE,CAAC;KAClC;IAED,OAAO,CAAO,OAAO,EAAE,QAAQ,EAAE,EAAE;QAC/B,MAAM,MAAM,GAAG,CAAC,MAAM,OAAO,CAAC,SAAS,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAqB,CAAC;QAChF,IAAI,CAAC,MAAM,EAAE;YACT,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;SAChE;QAED,MAAM,CAAC,GAAG,MAAM,IAAA,uBAAa,EAAC;YAC1B,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,IAAI,EAAE,OAAO,CAAC,IAAI;YAClB,KAAK,EAAE,OAAO,CAAC,KAA0C;YACzD,WAAW,EAAE,OAAO,CAAC,IAAI;YACzB,MAAM;YACN,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,UAAU,EAAE,OAAO;SACtB,CAAC,CAAC;QAEH,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IAC3C,CAAC,CAAA,CAAC;AACN,CAAC,CAAC;AAEF,kBAAe,OAAO,CAAC"}
@@ -0,0 +1 @@
1
+ export { default as ZenStackFastifyPlugin } from './plugin';
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ZenStackFastifyPlugin = void 0;
7
+ var plugin_1 = require("./plugin");
8
+ Object.defineProperty(exports, "ZenStackFastifyPlugin", { enumerable: true, get: function () { return __importDefault(plugin_1).default; } });
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/fastify/index.ts"],"names":[],"mappings":";;;;;;AAAA,mCAA4D;AAAnD,gIAAA,OAAO,OAAyB"}
@@ -0,0 +1,27 @@
1
+ import { ModelZodSchema } from '@zenstackhq/runtime/zod';
2
+ import { FastifyPluginCallback, FastifyReply, FastifyRequest } from 'fastify';
3
+ import { LoggerConfig } from '../openapi';
4
+ /**
5
+ * Fastify plugin options
6
+ */
7
+ export interface PluginOptions {
8
+ /**
9
+ * Url prefix, e.g.: /api
10
+ */
11
+ prefix: string;
12
+ /**
13
+ * Callback for getting a PrismaClient for the given request
14
+ */
15
+ getPrisma: (request: FastifyRequest, reply: FastifyReply) => unknown | Promise<unknown>;
16
+ /**
17
+ * Logger settings
18
+ */
19
+ logger?: LoggerConfig;
20
+ /**
21
+ * Zod schemas for validating request input. Pass `true` to load from standard location
22
+ * (need to enable `@core/zod` plugin in schema.zmodel) or omit to disable input validation.
23
+ */
24
+ zodSchemas?: ModelZodSchema | boolean;
25
+ }
26
+ declare const _default: FastifyPluginCallback<PluginOptions, import("fastify").RawServerDefault, import("fastify").FastifyTypeProviderDefault, import("fastify").FastifyBaseLogger>;
27
+ export default _default;
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const zod_1 = require("@zenstackhq/runtime/zod");
16
+ const fastify_plugin_1 = __importDefault(require("fastify-plugin"));
17
+ const openapi_1 = require("../openapi");
18
+ /**
19
+ * Fastify plugin for handling CRUD requests.
20
+ */
21
+ const pluginHandler = (fastify, options, done) => {
22
+ var _a, _b, _c, _d;
23
+ const prefix = (_a = options.prefix) !== null && _a !== void 0 ? _a : '';
24
+ if (((_b = options.logger) === null || _b === void 0 ? void 0 : _b.info) === undefined) {
25
+ console.log(`ZenStackPlugin installing routes at prefix: ${prefix}`);
26
+ }
27
+ else {
28
+ (_d = (_c = options.logger) === null || _c === void 0 ? void 0 : _c.info) === null || _d === void 0 ? void 0 : _d.call(_c, `ZenStackPlugin installing routes at prefix: ${prefix}`);
29
+ }
30
+ let schemas;
31
+ if (typeof options.zodSchemas === 'object') {
32
+ schemas = options.zodSchemas;
33
+ }
34
+ else if (options.zodSchemas === true) {
35
+ schemas = (0, zod_1.getModelZodSchemas)();
36
+ }
37
+ fastify.all(`${prefix}/*`, (request, reply) => __awaiter(void 0, void 0, void 0, function* () {
38
+ const prisma = (yield options.getPrisma(request, reply));
39
+ if (!prisma) {
40
+ throw new Error('unable to get prisma from request context');
41
+ }
42
+ const query = request.query;
43
+ const response = yield (0, openapi_1.handleRequest)({
44
+ method: request.method,
45
+ path: request.params['*'],
46
+ query,
47
+ requestBody: request.body,
48
+ prisma,
49
+ logger: options.logger,
50
+ zodSchemas: schemas,
51
+ });
52
+ reply.status(response.status).send(response.body);
53
+ }));
54
+ done();
55
+ };
56
+ exports.default = (0, fastify_plugin_1.default)(pluginHandler);
57
+ //# sourceMappingURL=plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../src/fastify/plugin.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAEA,iDAA6E;AAE7E,oEAAgC;AAChC,wCAAyD;AA4BzD;;GAEG;AACH,MAAM,aAAa,GAAyC,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE;;IACnF,MAAM,MAAM,GAAG,MAAA,OAAO,CAAC,MAAM,mCAAI,EAAE,CAAC;IAEpC,IAAI,CAAA,MAAA,OAAO,CAAC,MAAM,0CAAE,IAAI,MAAK,SAAS,EAAE;QACpC,OAAO,CAAC,GAAG,CAAC,+CAA+C,MAAM,EAAE,CAAC,CAAC;KACxE;SAAM;QACH,MAAA,MAAA,OAAO,CAAC,MAAM,0CAAE,IAAI,mDAAG,+CAA+C,MAAM,EAAE,CAAC,CAAC;KACnF;IAED,IAAI,OAAmC,CAAC;IACxC,IAAI,OAAO,OAAO,CAAC,UAAU,KAAK,QAAQ,EAAE;QACxC,OAAO,GAAG,OAAO,CAAC,UAAU,CAAC;KAChC;SAAM,IAAI,OAAO,CAAC,UAAU,KAAK,IAAI,EAAE;QACpC,OAAO,GAAG,IAAA,wBAAkB,GAAE,CAAC;KAClC;IAED,OAAO,CAAC,GAAG,CAAC,GAAG,MAAM,IAAI,EAAE,CAAO,OAAO,EAAE,KAAK,EAAE,EAAE;QAChD,MAAM,MAAM,GAAG,CAAC,MAAM,OAAO,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,CAAqB,CAAC;QAC7E,IAAI,CAAC,MAAM,EAAE;YACT,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;SAChE;QACD,MAAM,KAAK,GAAG,OAAO,CAAC,KAA+B,CAAC;QAEtD,MAAM,QAAQ,GAAG,MAAM,IAAA,uBAAa,EAAC;YACjC,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,IAAI,EAAG,OAAO,CAAC,MAAc,CAAC,GAAG,CAAC;YAClC,KAAK;YACL,WAAW,EAAE,OAAO,CAAC,IAAI;YACzB,MAAM;YACN,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,UAAU,EAAE,OAAO;SACtB,CAAC,CAAC;QAEH,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACtD,CAAC,CAAA,CAAC,CAAC;IAEH,IAAI,EAAE,CAAC;AACX,CAAC,CAAC;AAEF,kBAAe,IAAA,wBAAE,EAAC,aAAa,CAAC,CAAC"}
@@ -0,0 +1,46 @@
1
+ import { DbClientContract } from '@zenstackhq/runtime';
2
+ import type { ModelZodSchema } from '@zenstackhq/runtime/zod';
3
+ type LoggerMethod = (message: string, code?: string) => void;
4
+ /**
5
+ * Logger config.
6
+ */
7
+ export type LoggerConfig = {
8
+ debug?: LoggerMethod;
9
+ info?: LoggerMethod;
10
+ warn?: LoggerMethod;
11
+ error?: LoggerMethod;
12
+ };
13
+ /**
14
+ * Options for initializing a Next.js API endpoint request handler.
15
+ * @see requestHandler
16
+ */
17
+ export type RequestHandlerOptions = {
18
+ /**
19
+ * Logger configuration. By default log to console. Set to null to turn off logging.
20
+ */
21
+ logger?: LoggerConfig | null;
22
+ };
23
+ /**
24
+ * OpenApi request context.
25
+ */
26
+ export type RequestContext = {
27
+ method: string;
28
+ path: string;
29
+ query?: Record<string, string | string[]>;
30
+ requestBody?: unknown;
31
+ prisma: DbClientContract;
32
+ logger?: LoggerConfig;
33
+ zodSchemas?: ModelZodSchema;
34
+ };
35
+ /**
36
+ * OpenApi response.
37
+ */
38
+ export type Response = {
39
+ status: number;
40
+ body: unknown;
41
+ };
42
+ /**
43
+ * Handles OpenApi requests
44
+ */
45
+ export declare function handleRequest({ method, path, query, requestBody, prisma, logger, zodSchemas, }: RequestContext): Promise<Response>;
46
+ export {};
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.handleRequest = void 0;
13
+ const runtime_1 = require("@zenstackhq/runtime");
14
+ const change_case_1 = require("change-case");
15
+ const zod_validation_error_1 = require("zod-validation-error");
16
+ const utils_1 = require("./utils");
17
+ function getZodSchema(zodSchemas, model, operation) {
18
+ if (zodSchemas[model]) {
19
+ return zodSchemas[model][operation];
20
+ }
21
+ else if (zodSchemas[(0, change_case_1.pascalCase)(model)]) {
22
+ return zodSchemas[(0, change_case_1.pascalCase)(model)][operation];
23
+ }
24
+ else {
25
+ return undefined;
26
+ }
27
+ }
28
+ function zodValidate(zodSchemas, model, operation, args) {
29
+ const zodSchema = zodSchemas && getZodSchema(zodSchemas, model, operation);
30
+ if (zodSchema) {
31
+ const parseResult = zodSchema.safeParse(args);
32
+ if (parseResult.success) {
33
+ return { data: parseResult.data, error: undefined };
34
+ }
35
+ else {
36
+ return { data: undefined, error: (0, zod_validation_error_1.fromZodError)(parseResult.error).message };
37
+ }
38
+ }
39
+ else {
40
+ return { data: args, error: undefined };
41
+ }
42
+ }
43
+ /**
44
+ * Handles OpenApi requests
45
+ */
46
+ function handleRequest({ method, path, query, requestBody, prisma, logger, zodSchemas, }) {
47
+ var _a, _b;
48
+ return __awaiter(this, void 0, void 0, function* () {
49
+ const parts = path.split('/').filter((p) => !!p);
50
+ const op = parts.pop();
51
+ const model = parts.pop();
52
+ if (parts.length !== 0 || !op || !model) {
53
+ return { status: 400, body: { message: 'invalid request path' } };
54
+ }
55
+ method = method.toUpperCase();
56
+ const dbOp = op;
57
+ let args;
58
+ let resCode = 200;
59
+ switch (dbOp) {
60
+ case 'create':
61
+ case 'createMany':
62
+ case 'upsert':
63
+ if (method !== 'POST') {
64
+ return { status: 400, body: { message: 'invalid request method, only POST is supported' } };
65
+ }
66
+ if (!requestBody) {
67
+ return { status: 400, body: { message: 'missing request body' } };
68
+ }
69
+ args = requestBody;
70
+ // TODO: upsert's status code should be conditional
71
+ resCode = 201;
72
+ break;
73
+ case 'findFirst':
74
+ case 'findUnique':
75
+ case 'findMany':
76
+ case 'aggregate':
77
+ case 'groupBy':
78
+ case 'count':
79
+ if (method !== 'GET') {
80
+ return { status: 400, body: { message: 'invalid request method, only GET is supported' } };
81
+ }
82
+ try {
83
+ args = (query === null || query === void 0 ? void 0 : query.q) ? unmarshal(query.q) : {};
84
+ }
85
+ catch (_c) {
86
+ return { status: 400, body: { message: 'query param must contain valid JSON' } };
87
+ }
88
+ break;
89
+ case 'update':
90
+ case 'updateMany':
91
+ if (method !== 'PUT' && method !== 'PATCH') {
92
+ return { status: 400, body: { message: 'invalid request method, only PUT AND PATCH are supported' } };
93
+ }
94
+ if (!requestBody) {
95
+ return { status: 400, body: { message: 'missing request body' } };
96
+ }
97
+ args = requestBody;
98
+ break;
99
+ case 'delete':
100
+ case 'deleteMany':
101
+ if (method !== 'DELETE') {
102
+ return { status: 400, body: { message: 'invalid request method, only DELETE is supported' } };
103
+ }
104
+ try {
105
+ args = (query === null || query === void 0 ? void 0 : query.q) ? unmarshal(query.q) : {};
106
+ }
107
+ catch (_d) {
108
+ return { status: 400, body: { message: 'query param must contain valid JSON' } };
109
+ }
110
+ break;
111
+ default:
112
+ return { status: 400, body: { message: 'invalid operation: ' + op } };
113
+ }
114
+ if (zodSchemas) {
115
+ const { data, error } = zodValidate(zodSchemas, model, dbOp, args);
116
+ if (error) {
117
+ return { status: 400, body: { message: error } };
118
+ }
119
+ else {
120
+ args = data;
121
+ }
122
+ }
123
+ try {
124
+ if (!prisma[model]) {
125
+ return { status: 400, body: { message: `unknown model name: ${model}` } };
126
+ }
127
+ const result = yield prisma[model][dbOp](args);
128
+ (0, utils_1.stripAuxFields)(result);
129
+ return { status: resCode, body: result };
130
+ }
131
+ catch (err) {
132
+ if ((0, runtime_1.isPrismaClientKnownRequestError)(err)) {
133
+ logError(logger, err.code, err.message);
134
+ if (err.code === 'P2004') {
135
+ // rejected by policy
136
+ return {
137
+ status: 403,
138
+ body: {
139
+ prisma: true,
140
+ rejectedByPolicy: true,
141
+ code: err.code,
142
+ message: err.message,
143
+ reason: (_a = err.meta) === null || _a === void 0 ? void 0 : _a.reason,
144
+ },
145
+ };
146
+ }
147
+ else {
148
+ return {
149
+ status: 400,
150
+ body: {
151
+ prisma: true,
152
+ code: err.code,
153
+ message: err.message,
154
+ reason: (_b = err.meta) === null || _b === void 0 ? void 0 : _b.reason,
155
+ },
156
+ };
157
+ }
158
+ }
159
+ else if ((0, runtime_1.isPrismaClientUnknownRequestError)(err) || (0, runtime_1.isPrismaClientValidationError)(err)) {
160
+ logError(logger, err.message);
161
+ return {
162
+ status: 400,
163
+ body: {
164
+ prisma: true,
165
+ message: err.message,
166
+ },
167
+ };
168
+ }
169
+ else {
170
+ logError(logger, err.message);
171
+ return {
172
+ status: 400,
173
+ body: {
174
+ message: err.message,
175
+ },
176
+ };
177
+ }
178
+ }
179
+ });
180
+ }
181
+ exports.handleRequest = handleRequest;
182
+ function unmarshal(value) {
183
+ return JSON.parse(value);
184
+ }
185
+ function logError(logger, message, code) {
186
+ if (logger === undefined) {
187
+ console.error(`@zenstackhq/openapi: error ${code ? '[' + code + ']' : ''}, ${message}`);
188
+ }
189
+ else if (logger === null || logger === void 0 ? void 0 : logger.error) {
190
+ logger.error(message, code);
191
+ }
192
+ }
193
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/openapi/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,iDAM6B;AAE7B,6CAAyC;AACzC,+DAAoD;AACpD,mCAAyC;AA8CzC,SAAS,YAAY,CAAC,UAA0B,EAAE,KAAa,EAAE,SAA6B;IAC1F,IAAI,UAAU,CAAC,KAAK,CAAC,EAAE;QACnB,OAAO,UAAU,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC;KACvC;SAAM,IAAI,UAAU,CAAC,IAAA,wBAAU,EAAC,KAAK,CAAC,CAAC,EAAE;QACtC,OAAO,UAAU,CAAC,IAAA,wBAAU,EAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;KACnD;SAAM;QACH,OAAO,SAAS,CAAC;KACpB;AACL,CAAC;AAED,SAAS,WAAW,CAChB,UAAsC,EACtC,KAAa,EACb,SAA6B,EAC7B,IAAa;IAEb,MAAM,SAAS,GAAG,UAAU,IAAI,YAAY,CAAC,UAAU,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC;IAC3E,IAAI,SAAS,EAAE;QACX,MAAM,WAAW,GAAG,SAAS,CAAC,SAAS,CAAC,IA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CAAC,CAAC;gBACzC,OAAO;oBACH,MAAM,EAAE,GAAG;oBACX,IAAI,EAAE;wBACF,OAAO,EAAG,GAAa,CAAC,OAAO;qBAClC;iBACJ,CAAC;aACL;SACJ;;CACJ;AAhJD,sCAgJC;AAED,SAAS,SAAS,CAAC,KAAa;IAC5B,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,QAAQ,CAAC,MAAuC,EAAE,OAAe,EAAE,IAAa;IACrF,IAAI,MAAM,KAAK,SAAS,EAAE;QACtB,OAAO,CAAC,KAAK,CAAC,8BAA8B,IAAI,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,GAAG,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,OAAO,EAAE,CAAC,CAAC;KAC3F;SAAM,IAAI,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,KAAK,EAAE;QACtB,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;KAC/B;AACL,CAAC"}
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Recursively strip auxiliary fields from the given data.
3
+ */
4
+ export declare function stripAuxFields(data: unknown): void;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.stripAuxFields = void 0;
4
+ const sdk_1 = require("@zenstackhq/sdk");
5
+ /**
6
+ * Recursively strip auxiliary fields from the given data.
7
+ */
8
+ function stripAuxFields(data) {
9
+ if (Array.isArray(data)) {
10
+ return data.forEach(stripAuxFields);
11
+ }
12
+ else if (data && typeof data === 'object') {
13
+ for (const [key, value] of Object.entries(data)) {
14
+ if (sdk_1.AUXILIARY_FIELDS.includes(key)) {
15
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
16
+ delete data[key];
17
+ }
18
+ else {
19
+ stripAuxFields(value);
20
+ }
21
+ }
22
+ }
23
+ }
24
+ exports.stripAuxFields = stripAuxFields;
25
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/openapi/utils.ts"],"names":[],"mappings":";;;AAAA,yCAAmD;AAEnD;;GAEG;AACH,SAAgB,cAAc,CAAC,IAAa;IACxC,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;QACrB,OAAO,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;KACvC;SAAM,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACzC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;YAC7C,IAAI,sBAAgB,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;gBAChC,8DAA8D;gBAC9D,OAAQ,IAAY,CAAC,GAAG,CAAC,CAAC;aAC7B;iBAAM;gBACH,cAAc,CAAC,KAAK,CAAC,CAAC;aACzB;SACJ;KACJ;AACL,CAAC;AAbD,wCAaC"}
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@zenstackhq/server",
3
+ "version": "1.0.0-alpha.100",
4
+ "displayName": "ZenStack Server-side Adapters",
5
+ "description": "ZenStack server-side adapters",
6
+ "homepage": "https://zenstack.dev",
7
+ "publishConfig": {
8
+ "directory": "dist",
9
+ "linkDirectory": true
10
+ },
11
+ "keywords": [
12
+ "fastify"
13
+ ],
14
+ "author": "",
15
+ "license": "MIT",
16
+ "dependencies": {
17
+ "change-case": "^4.1.2",
18
+ "tiny-invariant": "^1.3.1",
19
+ "zod-validation-error": "^0.2.1",
20
+ "@zenstackhq/runtime": "1.0.0-alpha.100",
21
+ "@zenstackhq/sdk": "1.0.0-alpha.100",
22
+ "@zenstackhq/openapi": "1.0.0-alpha.100"
23
+ },
24
+ "devDependencies": {
25
+ "@types/body-parser": "^1.19.2",
26
+ "@types/express": "^4.17.17",
27
+ "@types/jest": "^29.4.0",
28
+ "@types/supertest": "^2.0.12",
29
+ "body-parser": "^1.20.2",
30
+ "copyfiles": "^2.4.1",
31
+ "express": "^4.18.2",
32
+ "fastify": "^4.14.1",
33
+ "fastify-plugin": "^4.5.0",
34
+ "jest": "^29.4.3",
35
+ "rimraf": "^3.0.2",
36
+ "supertest": "^6.3.3",
37
+ "ts-jest": "^29.0.5",
38
+ "typescript": "^4.9.4",
39
+ "@zenstackhq/testtools": "1.0.0-alpha.100"
40
+ },
41
+ "scripts": {
42
+ "clean": "rimraf dist",
43
+ "build": "pnpm lint && pnpm clean && tsc && copyfiles ./package.json ./README.md ./LICENSE dist",
44
+ "watch": "tsc --watch",
45
+ "lint": "eslint src --ext ts",
46
+ "test": "jest",
47
+ "publish-dev": "pnpm publish --tag dev"
48
+ }
49
+ }