Skip to content

Commit

Permalink
Merge pull request #8 from TypedProject/feat-cache-response
Browse files Browse the repository at this point in the history
feat: Cache response
  • Loading branch information
Romakita authored Mar 9, 2021
2 parents 475c426 + f857f80 commit 1cbf208
Show file tree
Hide file tree
Showing 11 changed files with 175 additions and 113 deletions.
42 changes: 26 additions & 16 deletions packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,20 @@
},
"dependencies": {
"@octokit/rest": "18.3.2",
"@tsed/ajv": "6.28.0",
"@tsed/async-hook-context": "6.28.0",
"@tsed/common": "6.28.0",
"@tsed/core": "6.28.0",
"@tsed/di": "6.28.0",
"@tsed/exceptions": "6.28.0",
"@tsed/formio": "6.28.0",
"@tsed/json-mapper": "6.28.0",
"@tsed/ajv": "6.32.0",
"@tsed/async-hook-context": "6.32.0",
"@tsed/common": "6.32.0",
"@tsed/core": "6.32.0",
"@tsed/di": "6.32.0",
"@tsed/exceptions": "6.32.0",
"@tsed/formio": "6.32.0",
"@tsed/json-mapper": "6.32.0",
"@tsed/logger-logentries": "5.6.0",
"@tsed/mongoose": "6.28.0",
"@tsed/passport": "6.28.0",
"@tsed/platform-express": "6.28.0",
"@tsed/schema": "6.28.0",
"@tsed/swagger": "6.28.0",
"@tsed/mongoose": "6.32.0",
"@tsed/passport": "6.32.0",
"@tsed/platform-express": "6.32.0",
"@tsed/schema": "6.32.0",
"@tsed/swagger": "6.32.0",
"ajv": "^7.0.4",
"body-parser": "^1.19.0",
"compression": "^1.7.4",
Expand All @@ -44,6 +44,8 @@
"formio": "2.0.0-rc.42",
"globby": "11.0.2",
"le_node": "^1.8.0",
"cache-manager": "3.4.1",
"cache-manager-mongoose": "0.0.4",
"method-override": "^3.0.0",
"moment": "2.29.1",
"mongoose": "^5.11.14",
Expand All @@ -68,6 +70,7 @@
"@types/passport": "^1.0.5",
"@types/supertest": "^2.0.10",
"@types/url-parse": "^1.4.3",
"@types/cache-manager": "3.4.0",
"concurrently": "^5.3.0",
"husky": "^5.0.9",
"jest": "^26.6.3",
Expand All @@ -76,9 +79,9 @@
"supertest": "^6.1.3",
"ts-jest": "^26.5.0",
"ts-node": "^9.1.1",
"ts-node-dev": "1.1.1",
"ts-node-dev": "^1.1.6",
"tsconfig-paths": "3.9.0",
"typescript": "^4.1.3"
"typescript": "^4.2.3"
},
"husky": {
"hooks": {
Expand All @@ -87,5 +90,12 @@
}
},
"workspaces": {},
"peerDependencies": {}
"peerDependencies": {},
"tsed": {
"convention": "std",
"paths": {
"middlewares": "<rootDir>/src/infra/middlewares",
"services": "<rootDir>/src/back"
}
}
}
24 changes: 18 additions & 6 deletions packages/server/src/Server.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,29 @@
import "@tsed/ajv";
import "@tsed/async-hook-context";
import {PlatformApplication, Res} from "@tsed/common";
import {Env} from "@tsed/core";
import {Configuration, Inject} from "@tsed/di";
import "@tsed/formio";
import "@tsed/mongoose";
import "@tsed/platform-express"; // /!\ keep this import
import "@tsed/swagger";
import bodyParser from "body-parser";
import compress from "compression";
import compression from "compression";
import cookieParser from "cookie-parser";
import cors from "cors";
import {ServerResponse} from "http";
import methodOverride from "method-override";
import mongoose from "mongoose";
import {join} from "path";
import {isProduction} from "./config/env";
import formioConfig from "./config/formio";
import "./config/logger";
import mongooseConfig from "./config/mongoose";
import swaggerConfig from "./config/swagger";
import "./config/logger";
import {VersionCtrl} from "./controllers/rest/version/VersionCtrl";
import {Env} from "@tsed/core";
import {EnsureHttpsMiddleware} from "./infra/middlewares/EnsureHttpsMiddleware";
import {EnsureHttpsMiddleware} from "./infra/middlewares/https/EnsureHttpsMiddleware";

const mongooseStore = require("cache-manager-mongoose");
const send = require("send");

export const rootDir = __dirname;
Expand Down Expand Up @@ -72,13 +74,23 @@ function setCustomCacheControl(res: ServerResponse, path: string) {
{env: Env.PROD, use: EnsureHttpsMiddleware},
cors(),
cookieParser(),
compress({}),
compression({}),
methodOverride(),
bodyParser.json(),
bodyParser.urlencoded({
extended: true
})
]
],
cache: {
ttl: 300,
store: mongooseStore,
mongoose,
modelName: "caches",
modelOptions: {
collection: "caches",
versionKey: false
}
}
})
export class Server {
@Inject()
Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/config/mongoose/default.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export default {
id: "default",
url: process.env.MONGOOSE_URL || "mongodb://localhost:27017/tsed-formio-example",
url: process.env.MONGOOSE_URL || "mongodb://localhost:27017/tsed-api",
connectionOptions: {
useNewUrlParser: true,
useUnifiedTopology: true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ describe("GithubCtrl", () => {
let request: SuperTest.SuperTest<SuperTest.Test>;
beforeAll(
TestMongooseContext.bootstrap(Server, {
cache: false,
mount: {
"/rest": [GithubCtrl]
}
Expand Down
15 changes: 11 additions & 4 deletions packages/server/src/controllers/rest/github/GithubCtrl.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {InjectContext} from "@tsed/async-hook-context";
import {Controller, Get, Inject, PathParams, PlatformContext} from "@tsed/common";
import {Controller, Get, Inject, PathParams, PlatformContext, UseCache} from "@tsed/common";
import {array, boolean, number, object, Returns, string} from "@tsed/schema";
import {GithubClient} from "../../../infra/back/github/GithubClient";

Expand Down Expand Up @@ -66,15 +66,16 @@ export class GithubCtrl {
@Inject()
protected client: GithubClient;

handleResponse({data, headers}: any) {
this.$ctx?.response.setHeader("etag", headers.etag);
this.$ctx?.response.setHeader("date", headers.date);
handleResponse({data}: any) {
return data;
}

@Get()
@(Returns(200).ContentType("application/json").Schema(GithubRepo))
@(Returns(401).Description("Repository unauthorized"))
@UseCache({
ttl: 600
})
async get(@PathParams("owner") owner: string, @PathParams("repo") repo: string) {
const data = await this.handleResponse(await this.client.repos.get({owner, repo}));

Expand All @@ -90,13 +91,19 @@ export class GithubCtrl {
@Get("/contributors")
@(Returns(200).ContentType("application/json").Schema(GithubContributors))
@(Returns(401).Description("Repository unauthorized"))
@UseCache({
ttl: 3600
})
async getContributors(@PathParams("owner") owner: string, @PathParams("repo") repo: string) {
return this.handleResponse(await this.client.repos.listContributors({owner, repo}));
}

@Get("/releases")
@(Returns(200).ContentType("application/json").Schema(GithubReleases))
@(Returns(401).Description("Repository unauthorized"))
@UseCache({
ttl: 3600
})
async getReleases(@PathParams("owner") owner: string, @PathParams("repo") repo: string) {
return this.handleResponse(await this.client.repos.listReleases({owner, repo}));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ describe("OpenCollectiveCtrl", () => {
let request: SuperTest.SuperTest<SuperTest.Test>;
beforeAll(
TestMongooseContext.bootstrap(Server, {
cache: false,
mount: {
"/rest": [OpenCollectiveCtrl]
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import {Controller, Get} from "@tsed/common";
import {Controller, Get, UseCache} from "@tsed/common";
import {Inject} from "@tsed/di";
import {any, array, boolean, datetime, email, number, object, Returns, string, url} from "@tsed/schema";
import {OpenCollectiveClient} from "../../../infra/back/opencollective/OpenCollectiveClient";

const ttl = Number(process.env.OPEN_COLLECTIVE_TTL || 3600);

const OpenCollectiveMemberSchema = object({
MemberId: number().required().example(13382),
createdAt: datetime().required().example("2018-03-01 22:31"),
Expand Down Expand Up @@ -33,6 +35,9 @@ export class OpenCollectiveCtrl {

@Get()
@(Returns(200).ContentType("application/json").Schema(OpenCollectiveMembersSchema))
@UseCache({
ttl
})
getMember() {
return this.client.getMembers("tsed");
}
Expand Down
2 changes: 1 addition & 1 deletion processes.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ module.exports = {
'apps': [
{
'script': 'packages/server/dist/index.js',
'instances': 1,
'instances': process.env.PM2_NB_INSTANCE || 1,
'exec_mode': 'cluster',
'out_file': defaultLogFile,
'error_file': defaultLogFile,
Expand Down
Loading

0 comments on commit 1cbf208

Please sign in to comment.