Skip to content

merge dev to main #551

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 0 additions & 21 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,6 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Generate for Todo Sample",
"program": "${workspaceFolder}/packages/schema/dist/bin/cli",
"cwd": "${workspaceFolder}/samples/todo/",
"args": [
"generate"
],
"request": "launch",
"skipFiles": ["<node_internals>/**"],
"type": "node",
"env": {
"NODE_PATH": "${workspaceFolder}/samples/todo/node_modules"
}
},
{
"name": "Attach",
"port": 9229,
Expand All @@ -42,13 +28,6 @@
"skipFiles": ["<node_internals>/**"],
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/packages/schema/bundle/**/*.js"]
},
{
"name": "Todo sample: debug server-side",
"type": "node-terminal",
"request": "launch",
"command": "pnpm dev",
"cwd": "${workspaceFolder}/samples/todo/"
}
]
}
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ Our goal is to let you save time writing boilerplate code and focus on building

## How it works

> Read full documentation at 👉🏻 [zenstack.dev](https://zenstack.dev).

ZenStack incrementally extends Prisma's power with the following four layers:

### 1. ZModel - an extended Prisma schema language
Expand Down Expand Up @@ -181,7 +183,11 @@ Check out the [Collaborative Todo App](https://zenstack-todo.vercel.app/) for a

## Community

Join our [discord server](https://go.zenstack.dev/chat) for chat and updates!
Join our [discord server](https://discord.gg/Ykhr738dUe) for chat and updates!

## Contributing

If you like ZenStack, join us to make it a better tool! Please use the [Contributing Guide](CONTRIBUTING.md) for details on how to get started, and don't hesitate to join [Discord](https://discord.gg/Ykhr738dUe) to share your thoughts.

## License

Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
{
"name": "zenstack-monorepo",
"version": "1.0.0-beta.3",
"version": "1.0.0-beta.4",
"description": "",
"scripts": {
"build": "pnpm -r build",
"test": "pnpm -r run test --silent",
"test-ci": "pnpm -r run test --silent",
"test": "ZENSTACK_TEST=1 pnpm -r run test --silent",
"test-ci": "ZENSTACK_TEST=1 pnpm -r run test --silent",
"lint": "pnpm -r lint",
"publish-all": "pnpm --filter \"./packages/**\" -r publish --access public",
"publish-preview": "pnpm --filter \"./packages/**\" -r publish --registry http://localhost:4873"
Expand Down
2 changes: 1 addition & 1 deletion packages/language/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/language",
"version": "1.0.0-beta.3",
"version": "1.0.0-beta.4",
"displayName": "ZenStack modeling language compiler",
"description": "ZenStack modeling language compiler",
"homepage": "https://zenstack.dev",
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/openapi/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/openapi",
"displayName": "ZenStack Plugin and Runtime for OpenAPI",
"version": "1.0.0-beta.3",
"version": "1.0.0-beta.4",
"description": "ZenStack plugin and runtime supporting OpenAPI",
"main": "index.js",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/swr/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/swr",
"displayName": "ZenStack plugin for generating SWR hooks",
"version": "1.0.0-beta.3",
"version": "1.0.0-beta.4",
"description": "ZenStack plugin for generating SWR hooks",
"main": "index.js",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/tanstack-query/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/tanstack-query",
"displayName": "ZenStack plugin for generating tanstack-query hooks",
"version": "1.0.0-beta.3",
"version": "1.0.0-beta.4",
"description": "ZenStack plugin for generating tanstack-query hooks",
"main": "index.js",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/trpc/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/trpc",
"displayName": "ZenStack plugin for tRPC",
"version": "1.0.0-beta.3",
"version": "1.0.0-beta.4",
"description": "ZenStack plugin for tRPC",
"main": "index.js",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/runtime",
"displayName": "ZenStack Runtime Library",
"version": "1.0.0-beta.3",
"version": "1.0.0-beta.4",
"description": "Runtime of ZenStack for both client-side and server-side environments.",
"repository": {
"type": "git",
Expand Down
18 changes: 11 additions & 7 deletions packages/runtime/src/enhancements/model-meta.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import { lowerCaseFirst } from 'lower-case-first';
import { ModelMeta } from './types';
import path from 'path';
import { ModelMeta } from './types';

/**
* Load model meta from standard location.
*/
export function getDefaultModelMeta(): ModelMeta {
try {
if (process.env.NODE_ENV === 'test') {
// handling the case when running as tests, resolve relative to CWD
return require(path.join(process.cwd(), 'node_modules', '.zenstack', 'model-meta'));
} else {
return require('.zenstack/model-meta').default;
}
// normal load
return require('.zenstack/model-meta').default;
} catch {
if (process.env.ZENSTACK_TEST === '1') {
try {
// special handling for running as tests, try resolving relative to CWD
return require(path.join(process.cwd(), 'node_modules', '.zenstack', 'model-meta')).default;
} catch {
throw new Error('Model meta cannot be loaded. Please make sure "zenstack generate" has been run.');
}
}
throw new Error('Model meta cannot be loaded. Please make sure "zenstack generate" has been run.');
}
}
Expand Down
21 changes: 20 additions & 1 deletion packages/runtime/src/enhancements/policy/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable @typescript-eslint/no-explicit-any */

import path from 'path';
import { AuthUser, DbClientContract } from '../../types';
import { getDefaultModelMeta } from '../model-meta';
import { makeProxy } from '../proxy';
Expand Down Expand Up @@ -74,9 +76,18 @@ export function withPolicy<DbClient extends object>(

function getDefaultPolicy(): PolicyDef {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
return require('.zenstack/policy').default;
} catch {
if (process.env.ZENSTACK_TEST === '1') {
try {
// special handling for running as tests, try resolving relative to CWD
return require(path.join(process.cwd(), 'node_modules', '.zenstack', 'policy')).default;
} catch {
throw new Error(
'Policy definition cannot be loaded from default location. Please make sure "zenstack generate" has been run.'
);
}
}
throw new Error(
'Policy definition cannot be loaded from default location. Please make sure "zenstack generate" has been run.'
);
Expand All @@ -88,6 +99,14 @@ function getDefaultZodSchemas(): ZodSchemas | undefined {
// eslint-disable-next-line @typescript-eslint/no-var-requires
return require('.zenstack/zod');
} catch {
if (process.env.ZENSTACK_TEST === '1') {
try {
// special handling for running as tests, try resolving relative to CWD
return require(path.join(process.cwd(), 'node_modules', '.zenstack', 'zod'));
} catch {
return undefined;
}
}
return undefined;
}
}
2 changes: 1 addition & 1 deletion packages/schema/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"publisher": "zenstack",
"displayName": "ZenStack Language Tools",
"description": "A toolkit for building secure CRUD apps with Next.js + Typescript",
"version": "1.0.0-beta.3",
"version": "1.0.0-beta.4",
"author": {
"name": "ZenStack Team"
},
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/sdk",
"version": "1.0.0-beta.3",
"version": "1.0.0-beta.4",
"description": "ZenStack plugin development SDK",
"main": "index.js",
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ export function getFunctionExpressionContext(funcDecl: FunctionDecl) {
const funcAllowedContext: ExpressionContext[] = [];
const funcAttr = funcDecl.attributes.find((attr) => attr.decl.$refText === '@@@expressionContext');
if (funcAttr) {
const contextArg = getAttributeArg(funcAttr, 'context');
const contextArg = funcAttr.args[0].value;
if (isArrayExpr(contextArg)) {
contextArg.items.forEach((item) => {
if (isEnumFieldReference(item)) {
Expand Down
2 changes: 1 addition & 1 deletion packages/server/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/server",
"version": "1.0.0-beta.3",
"version": "1.0.0-beta.4",
"displayName": "ZenStack Server-side Adapters",
"description": "ZenStack server-side adapters",
"homepage": "https://zenstack.dev",
Expand Down
43 changes: 36 additions & 7 deletions packages/server/src/express/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,17 @@ export interface MiddlewareOptions extends AdapterBaseOptions {
* Callback for getting a PrismaClient for the given request
*/
getPrisma: (req: Request, res: Response) => unknown | Promise<unknown>;

/**
* Controls if the middleware directly sends a response. If set to false,
* the response is stored in the `res.locals` object and then the middleware
* calls the `next()` function to pass the control to the next middleware.
* Subsequent middleware or request handlers need to make sure to send
* a response.
*
* Defaults to true;
*/
sendResponse?: boolean;
}

/**
Expand All @@ -33,13 +44,18 @@ const factory = (options: MiddlewareOptions): Handler => {
const requestHandler = options.handler || RPCAPIHandler();
const useSuperJson = options.useSuperJson === true;

return async (request, response) => {
return async (request, response, next) => {
const prisma = (await options.getPrisma(request, response)) as DbClientContract;
const { sendResponse } = options;

if (sendResponse === false && !prisma) {
throw new Error('unable to get prisma from request context');
}

if (!prisma) {
response
return response
.status(500)
.json(marshalToObject({ message: 'unable to get prisma from request context' }, useSuperJson));
return;
}

let query: Record<string, string | string[]> = {};
Expand All @@ -56,8 +72,10 @@ const factory = (options: MiddlewareOptions): Handler => {
}
query = buildUrlQuery(rawQuery, useSuperJson);
} catch {
response.status(400).json(marshalToObject({ message: 'invalid query parameters' }, useSuperJson));
return;
if (sendResponse === false) {
throw new Error('invalid query parameters');
}
return response.status(400).json(marshalToObject({ message: 'invalid query parameters' }, useSuperJson));
}

try {
Expand All @@ -71,9 +89,20 @@ const factory = (options: MiddlewareOptions): Handler => {
zodSchemas,
logger: options.logger,
});
response.status(r.status).json(marshalToObject(r.body, useSuperJson));
if (sendResponse === false) {
// attach response and pass control to the next middleware
response.locals = {
status: r.status,
body: r.body,
};
return next();
}
return response.status(r.status).json(marshalToObject(r.body, useSuperJson));
} catch (err) {
response
if (sendResponse === false) {
throw err;
}
return response
.status(500)
.json(marshalToObject({ message: `An unhandled error occurred: ${err}` }, useSuperJson));
}
Expand Down
27 changes: 27 additions & 0 deletions packages/server/tests/adapter/express.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,3 +251,30 @@ describe('Express adapter tests - rest handler', () => {
expect(await prisma.user.findMany()).toHaveLength(0);
});
});

describe('Express adapter tests - rest handler with customMiddleware', () => {
it('run middleware', async () => {
const { prisma, zodSchemas, modelMeta } = await loadSchema(schema);

const app = express();
app.use(bodyParser.json());
app.use(
'/api',
ZenStackMiddleware({
getPrisma: () => prisma,
modelMeta,
zodSchemas,
handler: RESTAPIHandler({ endpoint: 'http://localhost/api' }),
sendResponse: false,
})
);

app.use((req, res) => {
res.status(res.locals.status).json({ message: res.locals.body });
});

const r = await request(app).get(makeUrl('/api/post/1'));
expect(r.status).toBe(404);
expect(r.body.message).toHaveProperty('errors');
});
});
2 changes: 1 addition & 1 deletion packages/testtools/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/testtools",
"version": "1.0.0-beta.3",
"version": "1.0.0-beta.4",
"description": "ZenStack Test Tools",
"main": "index.js",
"publishConfig": {
Expand Down
4 changes: 2 additions & 2 deletions tests/integration/test-run/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.