Skip to content

Commit

Permalink
chore(platform-fastify): map request/reply methods to PlatformRequest…
Browse files Browse the repository at this point in the history
…/PlatformResponse

Closes: #2446, #2447
  • Loading branch information
Romakita committed Dec 30, 2023
1 parent ac65224 commit f00f933
Show file tree
Hide file tree
Showing 10 changed files with 173 additions and 311 deletions.
18 changes: 18 additions & 0 deletions packages/platform/platform-fastify/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html

module.exports = {
...require("@tsed/jest-config"),
roots: ["<rootDir>/src", "<rootDir>/test"],
moduleNameMapper: {
"^@tsed/platform-fastify$": "<rootDir>/src/index.ts"
},
coverageThreshold: {
global: {
statements: 98.28,
branches: 92.59,
functions: 100,
lines: 98.28
}
}
};
Original file line number Diff line number Diff line change
@@ -1,82 +1,33 @@
import {PlatformBuilder} from "@tsed/common";
import Sinon from "sinon";
import {expect} from "chai";
import {PlatformFastify} from "./PlatformFastify";

const sandbox = Sinon.createSandbox();

class Server {}

describe("PlatformFastify", () => {
describe("create()", () => {
beforeEach(() => {
sandbox.stub(PlatformBuilder, "create");
jest.spyOn(PlatformBuilder, "create").mockReturnValue({});
});
afterEach(() => sandbox.restore());
afterEach(() => jest.resetAllMocks());
it("should create platform", () => {
PlatformFastify.create(Server, {});

expect(PlatformBuilder.create).to.have.been.calledWithExactly(Server, {
expect(PlatformBuilder.create).toHaveBeenCalledWith(Server, {
adapter: PlatformFastify
});
});
});
describe("bootstrap()", () => {
beforeEach(() => {
sandbox.stub(PlatformBuilder, "bootstrap");
jest.spyOn(PlatformBuilder, "bootstrap").mockReturnValue({});
});
afterEach(() => sandbox.restore());
afterEach(() => jest.resetAllMocks());
it("should create platform", async () => {
await PlatformFastify.bootstrap(Server, {});

expect(PlatformBuilder.bootstrap).to.have.been.calledWithExactly(Server, {
expect(PlatformBuilder.bootstrap).toHaveBeenCalledWith(Server, {
adapter: PlatformFastify
});
});
});
describe("bodyParser()", () => {
afterEach(() => sandbox.restore());
it("should return the body parser (json) ", () => {
const stub = sandbox.stub().returns("body");

const platform = PlatformFastify.create(Server, {
fastify: {
bodyParser: stub
}
});

const result = platform.adapter.bodyParser("json", {strict: true});

expect(result).to.equal("body");
expect(stub).to.have.been.calledWithExactly({strict: true});
});
it("should return the body parser (raw) ", () => {
const stub = sandbox.stub().returns("body");

const platform = PlatformFastify.create(Server, {
fastify: {
bodyParser: stub
}
});

const result = platform.adapter.bodyParser("raw", {strict: true});

expect(result).to.equal("body");
expect(stub).to.have.been.calledWithExactly({strict: true});
});
it("should return the body parser (urlencoded) ", () => {
const stub = sandbox.stub().returns("body");

const platform = PlatformFastify.create(Server, {
fastify: {
bodyParser: stub
}
});

const result = platform.adapter.bodyParser("urlencoded", {strict: true});

expect(result).to.equal("body");
expect(stub).to.have.been.calledWithExactly({strict: true});
});
});
});
139 changes: 87 additions & 52 deletions packages/platform/platform-fastify/src/components/PlatformFastify.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
import middie from "@fastify/middie";
import {
createContext,
InjectorService,
PlatformAdapter,
PlatformApplication,
PlatformBuilder,
PlatformContext,
PlatformExceptions,
PlatformHandler,
PlatformMulter,
PlatformMulterSettings,
PlatformRequest,
PlatformResponse,
PlatformStaticsOptions,
runInContext
} from "@tsed/common";
import {Type} from "@tsed/core";
import {PlatformHandlerMetadata, PlatformLayer} from "@tsed/platform-router";
import next from "ajv/dist/vocabularies/next";
import Fastify, {FastifyInstance, FastifyReply, FastifyRequest} from "fastify";
import {PlatformFastifyApplication} from "../services/PlatformFastifyApplication";
import {PlatformFastifyHandler} from "../services/PlatformFastifyHandler";
import * as Http from "http";
import * as Https from "https";
import {PlatformFastifyRequest} from "../services/PlatformFastifyRequest";
import {PlatformFastifyResponse} from "../services/PlatformFastifyResponse";

Expand All @@ -33,28 +32,18 @@ declare global {
* @platform
* @fastify
*/
export class PlatformFastify implements PlatformAdapter<FastifyInstance> {
export class PlatformFastify extends PlatformAdapter<FastifyInstance> {
readonly providers = [
{
provide: PlatformApplication,
useClass: PlatformFastifyApplication
},
{
provide: PlatformResponse,
useClass: PlatformFastifyResponse
},
{
provide: PlatformRequest,
useClass: PlatformFastifyRequest
},
{
provide: PlatformHandler,
useClass: PlatformFastifyHandler
}
];

constructor(private injector: InjectorService) {}

/**
* Create new serverless application. In this mode, the component scan are disabled.
* @param module
Expand All @@ -79,20 +68,20 @@ export class PlatformFastify implements PlatformAdapter<FastifyInstance> {
});
}

onInit() {
// const injector = this.injector;
// const app = this.injector.get<PlatformApplication>(PlatformApplication)!;
//
// const listener: any = (error: any, ctx: F.Context) => {
// injector.get<PlatformExceptions>(PlatformExceptions)?.catch(error, ctx.request.$ctx);
// };
//
// app.getApp().silent = true;
// app.getApp().on("error", listener);
}
// onInit() {
// const injector = this.injector;
// const app = this.injector.get<PlatformApplication>(PlatformApplication)!;
//
// const listener: any = (error: any, ctx: F.Context) => {
// injector.get<PlatformExceptions>(PlatformExceptions)?.catch(error, ctx.request.$ctx);
// };
//
// app.getApp().silent = true;
// app.getApp().on("error", listener);
// }

mapLayers(layers: PlatformLayer[]) {
const app = this.getPlatformApplication();
const {app} = this;
const rawApp: FastifyInstance = app.getApp();

layers.forEach((layer) => {
Expand All @@ -105,22 +94,26 @@ export class PlatformFastify implements PlatformAdapter<FastifyInstance> {
rawApp.route({
method: layer.method,
url: layer.path,
handler: layer.handler
handler: async (req, reply) => {
for (const handler of layer.handlers) {
if (!reply.sent) {
await handler(req, reply);
}
}
}
});
});
}

mapHandler(handler: Function, metadata: PlatformHandlerMetadata) {
// if (metadata.isRawMiddleware()) {
// return handler;
// }
//
// return async (koaContext: Koa.Context, next: Koa.Next) => {
// const {$ctx} = koaContext.request;
// $ctx.next = next;
//
// await handler($ctx);
// };
if (metadata.isRawMiddleware()) {
return handler;
}

return (request: FastifyRequest, reply: FastifyReply) => {
const {$ctx} = request;
return runInContext(req.$ctx, () => handler($ctx));
};
}

useRouter(): this {
Expand All @@ -135,44 +128,66 @@ export class PlatformFastify implements PlatformAdapter<FastifyInstance> {
}

useContext(): this {
const app = this.getPlatformApplication();
const {app} = this;
const invoke = createContext(this.injector);

this.injector.logger.debug("Mount app context");

app.addHook("onRequest", async (request: FastifyRequest, reply: FastifyReply) => {
app.rawApp.addHook("onRequest", async (request, reply) => {
const $ctx = invoke({
request: request,
response: reply
});

await $ctx.start();

return runInContext($ctx, next);
});

app.addHook("onResponse", async () => {
app.rawApp.addHook("onResponse", async () => {
const $ctx = PlatformContext.get();
await $ctx.finish();
});

return this;
}

app() {
createApp() {
const {app, ...props} = this.injector.settings.get("fastify") || {};
const app: FastifyInstance = app || Fastify();
app.register(middie);
const httpPort = this.injector.settings.get("httpPort");
const httpOptions = this.injector.settings.get("httpOptions");
const httpsPort = settings.get("httpsPort");
const httpsOptions = settings.get("httpsOptions");

const instance: FastifyInstance =
app ||
Fastify({
...props,
http:
httpPort !== false
? {
...httpOptions
}
: null,
https:
httpsPort !== false
? {
...httpsOptions
}
: null
});

instance.decorateRequest("$ctx", null);
instance.decorateRequest("id", null);
instance.decorateReply("locals", null);

app.get("/test", (req, res) => {});
instance.register(middie);

app.addHook("onError", (request, reply, error) => {
instance.addHook("onError", (request, reply, error) => {
this.injector.get<PlatformExceptions>(PlatformExceptions)?.catch(error, ctx.request.$ctx);
});

return {
app,
callback: () => app
app: instance,
callback: () => () => instance
};
}

Expand All @@ -184,6 +199,26 @@ export class PlatformFastify implements PlatformAdapter<FastifyInstance> {
// return staticsMiddleware(options);
}

getServers(): any[] {
const httpsPort = this.injector.settings.get("httpsPort");
const httpPort = this.injector.settings.get("httpPort");

return [
createServer(this.injector, {
port: httpsPort,
type: "https",
token: Https.Server,
server: () => this.app.getApp().server
}),
createServer(this.injector, {
port: httpsPort ? null : httpPort,
type: "http",
token: Http.Server,
server: () => this.app.getApp().server
})
];
}

// bodyParser(type: "json" | "urlencoded" | "raw" | "text", additionalOptions: any = {}): any {
// // const opts = this.injector.settings.get(`koa.bodyParser`);
// // let parser: any = koaBodyParser;
Expand Down
9 changes: 0 additions & 9 deletions packages/platform/platform-fastify/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,7 @@

export * from "./exports";
export * from "./components/PlatformFastify";
export * from "./decorators/caseSensitive";
export * from "./decorators/ctx";
export * from "./decorators/routerSettings";
export * from "./decorators/state";
export * from "./decorators/strict";
export * from "./interfaces/PlatformFastifySettings";
export * from "./interfaces/interfaces";
export * from "./middlewares/resourceNotFoundMiddleware";
export * from "./middlewares/staticsMiddleware";
export * from "./services/PlatformFastifyHandler";
export * from "./services/PlatformFastifyRequest";
export * from "./services/PlatformFastifyResponse";
export * from "./utils/multer";
Loading

0 comments on commit f00f933

Please sign in to comment.