Skip to content
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
10 changes: 8 additions & 2 deletions packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,20 @@
"@zenstackhq/typescript-config": "workspace:*",
"@zenstackhq/vitest-config": "workspace:*",
"body-parser": "^2.2.0",
"supertest": "^7.1.4"
"supertest": "^7.1.4",
"express": "^5.0.0",
"next": "^15.0.0"
},
"peerDependencies": {
"express": "^5.0.0"
"express": "^5.0.0",
"next": "^15.0.0"
},
"peerDependenciesMeta": {
"express": {
"optional": true
},
"next": {
"optional": true
}
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import type { ClientContract } from '@zenstackhq/orm';
import type { SchemaDef } from '@zenstackhq/orm/schema';
import type { Handler, Request, Response } from 'express';
import type { ApiHandler } from '../types';
import type { ApiHandler } from '../../types';

/**
* Express middleware options
*/
export interface MiddlewareOptions<Schema extends SchemaDef> {
/**
* The API handler to process requests
*/
apiHandler: ApiHandler<Schema>;

/**
Expand Down
64 changes: 64 additions & 0 deletions packages/server/src/adapter/next/app-route-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import type { SchemaDef } from '@zenstackhq/orm/schema';
import { NextRequest, NextResponse } from 'next/server';
import type { AppRouteRequestHandlerOptions } from '.';

type Context = { params: Promise<{ path: string[] }> };

/**
* Creates a Next.js "app router" API route request handler that handles ZenStack CRUD requests.
*
* @param options Options for initialization
* @returns An API route request handler
*/
export default function factory<Schema extends SchemaDef>(
options: AppRouteRequestHandlerOptions<Schema>,
): (req: NextRequest, context: Context) => Promise<NextResponse> {
return async (req: NextRequest, context: Context) => {
const client = await options.getClient(req);
if (!client) {
return NextResponse.json({ message: 'unable to get ZenStackClient from request context' }, { status: 500 });
}

let params: Awaited<Context['params']>;
const url = new URL(req.url);
const query = Object.fromEntries(url.searchParams);

try {
params = await context.params;
} catch {
return NextResponse.json({ message: 'Failed to resolve request parameters' }, { status: 500 });
}

if (!params.path) {
return NextResponse.json(
{ message: 'missing path parameter' },
{
status: 400,
},
);
}
const path = params.path.join('/');

let requestBody: unknown;
if (req.body) {
try {
requestBody = await req.json();
} catch {
// noop
}
}

try {
const r = await options.apiHandler.handleRequest({
method: req.method!,
path,
query,
requestBody,
client,
});
return NextResponse.json(r.body, { status: r.status });
} catch (err) {
return NextResponse.json({ message: `An unhandled error occurred: ${err}` }, { status: 500 });
}
};
}
63 changes: 63 additions & 0 deletions packages/server/src/adapter/next/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import type { ClientContract } from '@zenstackhq/orm';
import type { SchemaDef } from '@zenstackhq/orm/schema';
import type { NextApiRequest, NextApiResponse } from 'next';
import type { NextRequest } from 'next/server';
import type { ApiHandler } from '../../types';
import { default as AppRouteHandler } from './app-route-handler';
import { default as PagesRouteHandler } from './pages-route-handler';

interface CommonAdapterOptions<Schema extends SchemaDef> {
/**
* The API handler to process requests
*/
apiHandler: ApiHandler<Schema>;
}

/**
* Options for initializing a Next.js API endpoint request handler.
*/
export interface PageRouteRequestHandlerOptions<Schema extends SchemaDef> extends CommonAdapterOptions<Schema> {
/**
* Callback for getting a ZenStackClient for the given request
*/
getClient: (req: NextApiRequest, res: NextApiResponse) => ClientContract<Schema> | Promise<ClientContract<Schema>>;

/**
* Use app dir or not
*/
useAppDir?: false | undefined;
}

/**
* Options for initializing a Next.js 13 app dir API route handler.
*/
export interface AppRouteRequestHandlerOptions<Schema extends SchemaDef> extends CommonAdapterOptions<Schema> {
/**
* Callback for getting a ZenStackClient for the given request.
*/
getClient: (req: NextRequest) => ClientContract<Schema> | Promise<ClientContract<Schema>>;

/**
* Use app dir or not
*/
useAppDir: true;
}

/**
* Creates a Next.js API route handler.
*/
export function NextRequestHandler<Schema extends SchemaDef>(
options: PageRouteRequestHandlerOptions<Schema>,
): ReturnType<typeof PagesRouteHandler>;
export function NextRequestHandler<Schema extends SchemaDef>(
options: AppRouteRequestHandlerOptions<Schema>,
): ReturnType<typeof AppRouteHandler>;
export function NextRequestHandler<Schema extends SchemaDef>(
options: PageRouteRequestHandlerOptions<Schema> | AppRouteRequestHandlerOptions<Schema>,
) {
if (options.useAppDir === true) {
return AppRouteHandler(options);
} else {
return PagesRouteHandler(options);
}
}
40 changes: 40 additions & 0 deletions packages/server/src/adapter/next/pages-route-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { SchemaDef } from '@zenstackhq/orm/schema';
import type { NextApiRequest, NextApiResponse } from 'next';
import type { PageRouteRequestHandlerOptions } from '.';

/**
* Creates a Next.js API endpoint "pages" router request handler that handles ZenStack CRUD requests.
*
* @param options Options for initialization
* @returns An API endpoint request handler
*/
export default function factory<Schema extends SchemaDef>(
options: PageRouteRequestHandlerOptions<Schema>,
): (req: NextApiRequest, res: NextApiResponse) => Promise<void> {
return async (req: NextApiRequest, res: NextApiResponse) => {
const client = await options.getClient(req, res);
if (!client) {
res.status(500).json({ message: 'unable to get ZenStackClient from request context' });
return;
}

if (!req.query['path']) {
res.status(400).json({ message: 'missing path parameter' });
return;
}
const path = (req.query['path'] as string[]).join('/');

try {
const r = await options.apiHandler.handleRequest({
method: req.method!,
path,
query: req.query as Record<string, string | string[]>,
requestBody: req.body,
client,
});
res.status(r.status).send(r.body);
} catch (err) {
res.status(500).send({ message: `An unhandled error occurred: ${err}` });
}
};
}
2 changes: 1 addition & 1 deletion packages/server/test/adapter/express.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import bodyParser from 'body-parser';
import express from 'express';
import request from 'supertest';
import { describe, expect, it } from 'vitest';
import { ZenStackMiddleware } from '../../src/adapter/express';
import { RPCApiHandler } from '../../src/api';
import { ZenStackMiddleware } from '../../src/express';
import { makeUrl, schema } from '../utils';

describe('Express adapter tests - rpc handler', () => {
Expand Down
Loading