Skip to content
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

feat(server): added express adapter #71

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
18 changes: 10 additions & 8 deletions apps/content/content/docs/server/integrations.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -67,24 +67,26 @@ server.listen(3000, () => {
import express from 'express'
import { ORPCHandler, CompositeHandler } from '@orpc/server/node'
import { OpenAPIServerlessHandler } from '@orpc/openapi/node'
import { expressAdapter } from '@orpc/server/express'
import { router } from 'examples/server'
import { ZodCoercer } from '@orpc/zod'

const openapiHandler = new OpenAPIServerlessHandler(router, {
const app = express()

const openAPIHandler = new OpenAPIServerlessHandler(router, {
schemaCoercers: [
new ZodCoercer(),
],
})

const orpcHandler = new ORPCHandler(router)
const compositeHandler = new CompositeHandler([openapiHandler, orpcHandler])

const app = express()
app.use(expressAdapter([orpcHandler, openAPIHandler], {
prefix: '/api',
}))

app.all('/api/*', (req, res) => {
return compositeHandler.handle(req, res, {
context: {},
prefix: '/api',
})
app.use((req, res, next) => {
res.status(404).send('Not Found')
})

app.listen(3000, () => {
Expand Down
7 changes: 7 additions & 0 deletions packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@
"import": "./dist/node.js",
"default": "./dist/node.js"
},
"./express": {
"types": "./dist/src/adapters/express/index.d.ts",
"import": "./dist/express.js",
"default": "./dist/express.js"
},
"./🔒/*": {
"types": "./dist/src/*.d.ts"
}
Expand All @@ -39,6 +44,7 @@
".": "./src/index.ts",
"./fetch": "./src/adapters/fetch/index.ts",
"./node": "./src/adapters/node/index.ts",
"./express": "./src/adapters/express/index.ts",
"./🔒/*": {
"types": "./src/*.ts"
}
Expand All @@ -59,6 +65,7 @@
"@orpc/shared": "workspace:*"
},
"devDependencies": {
"@types/express": "^5.0.0",
"zod": "^3.24.1"
}
}
30 changes: 30 additions & 0 deletions packages/server/src/adapters/express/composite-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { IncomingMessage, ServerResponse } from 'node:http'
import type { Context } from '../../types'
import type { ConditionalRequestHandler, RequestHandler, RequestOptions } from './types'

export class CompositeHandler<T extends Context> implements RequestHandler<T> {
constructor(
private readonly handlers: ConditionalRequestHandler<T>[],
) {}

async handle(req: IncomingMessage, res: ServerResponse, ...opt: [options: RequestOptions<T>] | (undefined extends T ? [] : never)): Promise<void> {
const len = this.handlers.length
const handlers = this.handlers

if (len > 0) {
const handler = handlers[0]!
if (handler.condition(req)) {
return handler.handle(req, res, ...opt)
}
}

for (let i = 1; i < len; i++) {
const handler = handlers[i]!
if (handler.condition(req)) {
return handler.handle(req, res, ...opt)
}
}

res.statusCode = 404
}
}
3 changes: 3 additions & 0 deletions packages/server/src/adapters/express/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './composite-handler'
export * from './middleware'
export * from './types'
22 changes: 22 additions & 0 deletions packages/server/src/adapters/express/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { ConditionalRequestHandler, RequestHandler, RequestOptions } from '@orpc/server/express'
import type { NextFunction, Request, Response } from 'express'
import type { Context } from '../../types'
import { CompositeHandler } from '@orpc/server/express'

export function expressAdapter<T extends Context>(
handlers: (ConditionalRequestHandler<T> | RequestHandler<T>)[],
options?: Partial<RequestOptions<T>>,
) {
const compositeHandler = new CompositeHandler(handlers as ConditionalRequestHandler<T>[])

return (req: Request, res: Response, next: NextFunction) => {
Promise.resolve()
.then(() =>
compositeHandler.handle(req, res, ...(options ? [options as RequestOptions<T>] : [undefined as any])),
)
.then(() => {
next()
})
.catch(next)
}
}
24 changes: 24 additions & 0 deletions packages/server/src/adapters/express/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/// <reference types="node" />

import type { RequestOptions as BaseRequestOptions } from '@mjackson/node-fetch-server'
import type { HTTPPath } from '@orpc/contract'
import type { Promisable } from '@orpc/shared'
import type { IncomingMessage, ServerResponse } from 'node:http'
import type { Context, WithSignal } from '../../types'

export type RequestOptions<T extends Context> =
& BaseRequestOptions
& WithSignal
& { prefix?: HTTPPath }
& (undefined extends T ? { context?: T } : { context: T })
& {
beforeSend?: (response: Response, context: T) => Promisable<void>
}

export interface RequestHandler<T extends Context> {
handle: (req: IncomingMessage, res: ServerResponse, ...opt: [options: RequestOptions<T>] | (undefined extends T ? [] : never)) => void
}

export interface ConditionalRequestHandler<T extends Context> extends RequestHandler<T> {
condition: (request: IncomingMessage) => boolean
}
24 changes: 8 additions & 16 deletions playgrounds/expressjs/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { OpenAPIGenerator } from '@orpc/openapi'
import { OpenAPIServerHandler } from '@orpc/openapi/node'
import { CompositeHandler, ORPCHandler } from '@orpc/server/node'
import { expressAdapter } from '@orpc/server/express'
import { ORPCHandler } from '@orpc/server/node'
import { ZodCoercer, ZodToJsonSchemaConverter } from '@orpc/zod'
import express from 'express'
import { router } from './router'
Expand All @@ -17,23 +18,14 @@ const openAPIHandler = new OpenAPIServerHandler(router, {
},
})

const orpcHandler = new ORPCHandler(router, {
onError: ({ error }) => {
console.error(error)
},
})

const compositeHandler = new CompositeHandler([openAPIHandler, orpcHandler])
const orpcHandler = new ORPCHandler(router)

app.all('/api/*', (req, res) => {
const context = req.headers.authorization
? { user: { id: 'test', name: 'John Doe', email: '[email protected]' } }
: {}
app.use(expressAdapter([orpcHandler, openAPIHandler], {
prefix: '/api',
}))

return compositeHandler.handle(req, res, {
prefix: '/api',
context,
})
app.use((req, res, next) => {
res.status(404).send('Not Found')
})

const openAPIGenerator = new OpenAPIGenerator({
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

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

Loading