Skip to content

Commit

Permalink
feat(trpc): bump support for 10.x
Browse files Browse the repository at this point in the history
  • Loading branch information
H4ad committed Jun 9, 2023
1 parent f78160f commit 5d3124a
Show file tree
Hide file tree
Showing 7 changed files with 68 additions and 63 deletions.
12 changes: 8 additions & 4 deletions package-lock.json

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

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@
"@semantic-release/exec": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^9.0.2",
"@trpc/server": "^9.27.4",
"@trpc/server": "^10.29.1",
"@types/aws-lambda": "^8.10.115",
"@types/body-parser": "^1.19.2",
"@types/cors": "^2.8.13",
Expand Down Expand Up @@ -137,7 +137,7 @@
"@deepkit/http": ">= 1.0.1-alpha.94",
"@google-cloud/functions-framework": ">= 3.0.0",
"@hapi/hapi": ">= 21.0.0",
"@trpc/server": ">= 9.0.0",
"@trpc/server": ">= 10.0.0",
"@types/aws-lambda": ">= 8.10.92",
"@types/body-parser": ">= 1.19.2",
"@types/cors": ">= 2.8.12",
Expand Down
14 changes: 8 additions & 6 deletions src/frameworks/trpc/trpc.framework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ export type TrpcAdapterContext<TContext> = TContext & TrpcAdapterBaseContext;
* @public
*/
export type TrpcFrameworkOptions<TContext> = Omit<
NodeHTTPHandlerOptions<AnyRouter<TContext>, IncomingMessage, ServerResponse>,
NodeHTTPHandlerOptions<AnyRouter, IncomingMessage, ServerResponse>,
'router' | 'createContext'
> & {
createContext?: (
Expand All @@ -150,8 +150,10 @@ export type TrpcFrameworkOptions<TContext> = Omit<
* @breadcrumb Frameworks / TrpcFramework
* @public
*/
export class TrpcFramework<TContext extends TrpcAdapterBaseContext>
implements FrameworkContract<AnyRouter<TContext>>
export class TrpcFramework<
TContext extends TrpcAdapterBaseContext,
TRouter extends AnyRouter = AnyRouter,
> implements FrameworkContract<TRouter>
{
//#region Constructor

Expand All @@ -167,8 +169,8 @@ export class TrpcFramework<TContext extends TrpcAdapterBaseContext>
/**
* {@inheritDoc}
*/
public sendRequest(
app: AnyRouter<TContext>,
public sendRequest<TRouter extends AnyRouter>(
app: TRouter,
request: IncomingMessage,
response: ServerResponse,
): void {
Expand Down Expand Up @@ -222,7 +224,7 @@ export class TrpcFramework<TContext extends TrpcAdapterBaseContext>
>,
): TContext | Promise<TContext> {
const createContextFromOptions: NodeHTTPCreateContextFn<
AnyRouter<Omit<TContext, keyof TrpcAdapterBaseContext>>,
AnyRouter,
IncomingMessage,
ServerResponse
> = getDefaultIfUndefined(
Expand Down
15 changes: 8 additions & 7 deletions test/frameworks/body-parser.framework.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,20 +366,21 @@ describe('BodyParserFramework', () => {
: it;

itFn(bodyParserTest.name, async () => {
const app = trpc
.router<TrpcAdapterContext<unknown>>()
.mutation('body', {
input: inp => inp,
resolve: ctx => {
const t = trpc.initTRPC.context<TrpcAdapterContext<unknown>>().create();

const app = t.router({
body: t.procedure
.input(inp => inp)
.mutation(ctx => {
const body = (ctx.ctx.request as any).body;

if (bodyParserTest.expectedBody)
expect(body).toEqual(bodyParserTest.expectedBody);
else expect(body).not.toEqual(bodyParserTest.notExpectedBody);

return 'ok';
},
});
}),
});

await handleRestExpects(app, new TrpcFramework(), bodyParserTest);
});
Expand Down
10 changes: 6 additions & 4 deletions test/frameworks/cors.framework.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ async function handleRestExpects<TApp>(
else expect(spySendRequest).not.toHaveBeenCalled();
}

describe(CorsFramework.name, () => {
describe('CorsFramework', () => {
describe('express', () => {
for (const corsTest of corsOptions) {
it(`${corsTest.method}: ${corsTest.name}`, async () => {
Expand Down Expand Up @@ -275,10 +275,12 @@ describe(CorsFramework.name, () => {
describe('trpc', () => {
for (const corsTest of corsOptions) {
it(`${corsTest.method}: ${corsTest.name}`, async () => {
const app = trpc.router();
const t = trpc.initTRPC.create();

app.query('/', {
resolve: () => 'ok',
const app = t.router({
['/']: t.procedure.query(() => {
return 'ok';
}),
});

await handleRestExpects(app, new TrpcFramework(), corsTest);
Expand Down
63 changes: 32 additions & 31 deletions test/frameworks/trpc.framework.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,11 @@ type TrpcContext = TrpcAdapterContext<unknown>;

function createHandler(
method: 'get' | 'post' | 'delete' | 'put',
): TestRouteBuilderHandler<AnyRouter<TrpcContext>, AnyRouter<TrpcContext>> {
): TestRouteBuilderHandler<ReturnType<typeof createRouter>, AnyRouter> {
return (app, path, handler) => {
if (method === 'get') {
return app.query(path, {
input: inp => inp,
resolve: ({ ctx, input }) => {
return app.router({
[path]: app.procedure.query(({ ctx, input }) => {
const [statusCode, resultBody, headers] = handler(
ctx.getHeaders(),
input,
Expand All @@ -36,38 +35,39 @@ function createHandler(
ctx.setStatus(statusCode);

return resultBody;
},
}),
});
} else {
return app.mutation(path, {
input: inp => inp,
resolve: ({ ctx, input }) => {
const [statusCode, resultBody, headers] = handler(
ctx.getHeaders(),
input,
);
return app.router({
[path]: app.procedure
.input(inp => inp)
.mutation(({ ctx, input }) => {
const [statusCode, resultBody, headers] = handler(
ctx.getHeaders(),
input,
);

for (const header of Object.keys(headers))
ctx.setHeader(header, headers[header]);
for (const header of Object.keys(headers))
ctx.setHeader(header, headers[header]);

ctx.setStatus(statusCode);
ctx.setStatus(statusCode);

return resultBody;
},
return resultBody;
}),
});
}
};
}

function createRouter() {
return trpc.router<TrpcContext>();
return trpc.initTRPC.context<TrpcContext>().create();
}

const validTestOptions = frameworkTestOptions.filter(
([method]) => method === 'post' || method === 'get',
);

describe(TrpcFramework.name, () => {
describe('TrpcFramework', () => {
for (const [
method,
path,
Expand Down Expand Up @@ -138,11 +138,11 @@ describe(TrpcFramework.name, () => {

const resultBody = ServerlessResponse.body(response);

expect(resultBody.toString('utf-8')).toEqual(
expect(
expectedValue !== undefined
? expectedValue
: JSON.stringify({ id: null, result: { type: 'data', data: body } }),
);
: JSON.stringify({ result: { data: body } }),
).toEqual(resultBody.toString('utf-8'));
expect(response.statusCode).toBe(statusCode);
expect(ServerlessResponse.headers(response)).toHaveProperty(
'response-header',
Expand All @@ -156,13 +156,13 @@ describe(TrpcFramework.name, () => {
type CustomContext = TrpcAdapterContext<Context>;

const currentDate = new Date();

const app = trpc.router<CustomContext>().query('test', {
resolve: function ({ ctx }) {
const t = trpc.initTRPC.context<CustomContext>().create();
const app = t.router({
test: t.procedure.query(function ({ ctx }) {
expect(ctx).toHaveProperty('currentDate');

ctx.setStatus(201);
},
}),
});

const request = new ServerlessRequest({
Expand Down Expand Up @@ -201,17 +201,17 @@ describe(TrpcFramework.name, () => {
const secondResultBody = ServerlessResponse.body(secondResponse);

const emptyResponse = JSON.stringify({
id: null,
result: { type: 'data' },
result: {},
});

expect(firstResultBody.toString('utf-8')).toEqual(emptyResponse);
expect(secondResultBody.toString('utf-8')).toEqual(emptyResponse);
});

it('should correctly send default methods inside context', async () => {
const app = createRouter().query('test', {
resolve: function ({ ctx }) {
const t = createRouter();
const app = t.router({
test: t.procedure.query(({ ctx }) => {
expect(ctx.request).toBeDefined();
expect(ctx.response).toBeDefined();

Expand All @@ -225,8 +225,9 @@ describe(TrpcFramework.name, () => {
ctx.setStatus(204);
ctx.setHeader('test2', 'batata');
ctx.removeHeader('test2');
},
}),
});

const framework = new TrpcFramework<TrpcAdapterContext<unknown>>();

const request = new ServerlessRequest({
Expand Down
13 changes: 4 additions & 9 deletions test/handlers/huawei.handler.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as http from 'http';
import { describe, expect, it, vitest } from 'vitest';
import supertest from 'supertest';
import { describe, expect, it, vitest } from 'vitest';
import { ILogger } from '../../src';
import { DummyAdapter } from '../../src/adapters/dummy';
import {
Expand All @@ -10,7 +10,7 @@ import {
import { DummyResolver } from '../../src/resolvers/dummy';
import { FrameworkMock } from '../mocks/framework.mock';

describe(HttpHuaweiHandler.name, () => {
describe('HttpHuaweiHandler', () => {
const app = null;

const response = { batata: true };
Expand All @@ -28,7 +28,7 @@ describe(HttpHuaweiHandler.name, () => {

it('should create correctly mocked server and test default constants', async () => {
const listenMock = vitest.fn();
const closeMock = vitest.fn();
const closeMock = vitest.fn(callback => callback());
const addEventListenerMock = vitest.fn();
const createServerMock = vitest.fn(
() =>
Expand All @@ -55,12 +55,7 @@ describe(HttpHuaweiHandler.name, () => {
logger,
);

expect(addEventListenerMock).toHaveBeenCalledWith(
'request',
expect.any(Function),
);

expect(createServerMock).toHaveBeenCalledWith(app, framework);
expect(createServerMock).toHaveBeenCalledWith(expect.any(Function));
expect(listenMock).toHaveBeenCalledWith(
DEFAULT_HUAWEI_LISTEN_PORT,
expect.any(Function),
Expand Down

0 comments on commit 5d3124a

Please sign in to comment.