@benpsnyder/analogjs-esm-trpc
Version:
Angular/Nitro-based tRPC integration
80 lines (76 loc) • 2.82 kB
JavaScript
import { resolveHTTPResponse } from '@trpc/server/http';
import { TRPCError } from '@trpc/server';
import { createURL } from 'ufo';
import { defineEventHandler, createError, isMethod, readBody } from 'h3';
/**
* ALl credit goes to the awesome trpc-nuxt plugin https://github.com/wobsoriano/trpc-nuxt
* Since Analog currently uses Nitro as the underlying server we can
* simply reuse the hard work done by Robert Soriano and friends
* **/
function getPath(event) {
const { params } = event.context;
if (typeof params?.['trpc'] === 'string') {
return params['trpc'];
}
if (params?.['trpc'] && Array.isArray(params['trpc'])) {
return params['trpc'].join('/');
}
return null;
}
function createTrpcNitroHandler({ router, createContext, responseMeta, onError, batching, }) {
return defineEventHandler(async (event) => {
const { req, res } = event.node;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const $url = createURL(req.url);
const path = getPath(event);
if (path === null) {
const error = router.getErrorShape({
error: new TRPCError({
message: 'Param "trpc" not found - is the file named `[trpc]`.ts or `[...trpc].ts`?',
code: 'INTERNAL_SERVER_ERROR',
}),
type: 'unknown',
ctx: undefined,
path: undefined,
input: undefined,
});
throw createError({
statusCode: 500,
statusMessage: JSON.stringify(error),
});
}
const httpResponse = await resolveHTTPResponse({
batching,
router,
req: {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
method: req.method,
headers: req.headers,
body: isMethod(event, 'GET') ? null : await readBody(event),
query: $url.searchParams,
},
path,
createContext: async () => await createContext?.(event),
responseMeta,
onError: (o) => {
onError?.({
...o,
req,
});
},
});
const { status, headers, body } = httpResponse;
res.statusCode = status;
headers &&
Object.keys(headers).forEach((key) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
res.setHeader(key, headers[key]);
});
return body;
});
}
/**
* Generated bundle index. Do not edit.
*/
export { createTrpcNitroHandler };
//# sourceMappingURL=benpsnyder-analogjs-esm-trpc-server.mjs.map