Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
ba1128f
merge dev to main (#315)
ymc9 Mar 31, 2023
e3993c5
merge dev to main (#319)
ymc9 Mar 31, 2023
e17acc7
merge dev to main (#340)
ymc9 Apr 11, 2023
4d35a0f
merge dev to main (#342)
ymc9 Apr 11, 2023
7b06837
merge dev to main (#345)
ymc9 Apr 13, 2023
3b4e67f
merge dev to main (#348)
ymc9 Apr 13, 2023
cd0cab3
merge dev to main (#353)
ymc9 Apr 14, 2023
097fc16
merge dev to main (#365)
jiashengguo Apr 30, 2023
e959463
merge dev to main (#372)
ymc9 May 1, 2023
f20eeca
merge dev to main (#374)
ymc9 May 1, 2023
7e46ea6
merge dev to main (#377)
ymc9 May 3, 2023
8e91c2c
chore: update README links
ymc9 May 3, 2023
2de180b
chore: update README links (#382)
ymc9 May 4, 2023
3fdb686
merge dev to main (#400)
ymc9 May 6, 2023
e2efc40
merge dev to main (#404)
ymc9 May 7, 2023
ec51e52
merge dev to main (#407)
ymc9 May 8, 2023
5890e98
merge dev to main (#425)
ymc9 May 28, 2023
831b32c
merge dev to main (#436)
ymc9 May 29, 2023
c5bab7e
merge dev to main (#440)
ymc9 May 30, 2023
a681c94
merge dev to main (#442)
ymc9 May 30, 2023
23943df
merge dev to main (#445)
jiashengguo Jun 1, 2023
f58b504
merge dev to main (#447)
ymc9 Jun 2, 2023
afa2388
merge dev to main (#453)
ymc9 Jun 3, 2023
4417792
merge dev to main (#458)
ymc9 Jun 4, 2023
d5fa3df
dev to main (#468)
ymc9 Jun 6, 2023
0dd6867
merge dev to main (#474)
ymc9 Jun 8, 2023
0bc3cb5
merge dev to main (#490)
ymc9 Jun 15, 2023
f31e0a2
merge dev to main (#494)
ymc9 Jun 15, 2023
cce305b
merge dev to main (#497)
ymc9 Jun 19, 2023
a70aa42
changes: add option to manage response middleware
chemitaxis Jul 1, 2023
73e0076
changes: improve comment
chemitaxis Jul 1, 2023
ebf8c26
changes: all paths return something
chemitaxis Jul 1, 2023
1503fc1
temp: added temporal express test for faster testing
chemitaxis Jul 2, 2023
d3448ee
changes: added test for manage custom middleware
chemitaxis Jul 3, 2023
52983b9
changes: fix everything about jest
chemitaxis Jul 3, 2023
86c08c9
changes: remove console.log
chemitaxis Jul 3, 2023
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
39 changes: 32 additions & 7 deletions packages/server/src/express/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ export interface MiddlewareOptions extends AdapterBaseOptions {
* Callback for getting a PrismaClient for the given request
*/
getPrisma: (req: Request, res: Response) => unknown | Promise<unknown>;
/**
* This option is used to enable/disable the option to manage the response
* by the middleware. If set to true, the middleware will not send the
* response and the user will be responsible for sending the response.
*
* Defaults to false;
*/
manageCustomResponse?: boolean;
}

/**
Expand All @@ -30,13 +38,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 { manageCustomResponse } = options;

if (manageCustomResponse && !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 @@ -53,8 +66,10 @@ const factory = (options: MiddlewareOptions): Handler => {
}
query = buildUrlQuery(rawQuery, useSuperJson);
} catch {
response.status(400).json(marshalToObject({ message: 'invalid query parameters' }, useSuperJson));
return;
if (manageCustomResponse) {
throw new Error('invalid query parameters');
}
return response.status(400).json(marshalToObject({ message: 'invalid query parameters' }, useSuperJson));
}

try {
Expand All @@ -68,9 +83,19 @@ const factory = (options: MiddlewareOptions): Handler => {
zodSchemas,
logger: options.logger,
});
response.status(r.status).json(marshalToObject(r.body, useSuperJson));
if (manageCustomResponse) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just to make sure I understand how to use this. Since when manageCustomResponse is on the code here, simply returns the status and body, is it supposed to use the middleware like regular function call in a request handler then?

const zenstack = ZenStackMiddleware({ manageCustomResponse: true, ... });

app.all('/api/model/*', async (req, res) => {
    const { status, body } = await zenstack(req, res);
    // more processing
    ...
    return res.status(status).json(body);
});

response.locals = {
status: r.status,
body: r.body,
};
return next();
}
return response.status(r.status).json(marshalToObject(r.body, useSuperJson));
} catch (err) {
response
if (manageCustomResponse) {
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' }),
manageCustomResponse: true,
})
);

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');
});
});