Skip to content

Commit

Permalink
Add basic caching
Browse files Browse the repository at this point in the history
  • Loading branch information
cowuake committed Oct 13, 2024
1 parent 53ca1ed commit be7ce40
Show file tree
Hide file tree
Showing 7 changed files with 149 additions and 4 deletions.
80 changes: 80 additions & 0 deletions package-lock.json

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

8 changes: 7 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,17 @@
"build": "npm run clean && npx tsc -p tsconfig.json",
"start": "node dist/src/server.js"
},
"keywords": ["fastify", "typescript", "mongodb", "restful-api"],
"keywords": [
"fastify",
"typescript",
"mongodb",
"restful-api"
],
"author": "Riccardo Mura",
"license": "MIT",
"dependencies": {
"@fastify/autoload": "^6.0.2",
"@fastify/caching": "^9.0.1",
"@fastify/env": "^5.0.1",
"@fastify/mongodb": "^9.0.1",
"@fastify/swagger": "^9.1.0",
Expand Down
51 changes: 51 additions & 0 deletions src/plugins/cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { FastifyInstance, RouteOptions } from 'fastify';
import fp from 'fastify-plugin';
import * as CacheUtils from '../utils/cache-utils';

module.exports = fp(async (fastify: FastifyInstance) => {
fastify.addHook('onRequest', async (request, reply) => {
const routeOptions = request.routeOptions as RouteOptions;
if (!routeOptions.schema?.tags?.includes('Cache')) {
return;
}

const cacheKey = CacheUtils.genCacheKey(request);
fastify.cache.get(cacheKey, (err, value) => {
if (err) {
fastify.log.error(err);
return;
}
if (!!value) {
const payload = JSON.parse(value.item as string);
fastify.log.info(`Cache hit for key: ${cacheKey}`);
reply.send(payload);
}
});
});

fastify.addHook('onSend', async (request, reply, payload) => {
const routeOptions = request.routeOptions as RouteOptions;
if (!routeOptions.schema?.tags?.includes('Cache') || reply.statusCode !== 200) {
return;
}

const cacheKey = CacheUtils.genCacheKey(request);
fastify.cache.get(cacheKey, (err, value) => {
if (err) {
fastify.log.error(err);
return;
}
if (!value) {
fastify.cache.set(cacheKey, payload, 10000, (err) => {
if (err) {
fastify.log.error(err);
}
});
}
});
});

fastify.addHook('onResponse', async (request, reply) => {
fastify.cache;
});
});
2 changes: 1 addition & 1 deletion src/routes/mflix/movies/base-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const routes: RouteOptions[] = [
method: HttpMethods.GET,
url,
schema: {
tags,
tags: [...tags, 'Cache'],
querystring: ListMoviesRequestSchema.properties.querystring,
response: {
200: ListMoviesResponseSchema.properties.body
Expand Down
2 changes: 1 addition & 1 deletion src/routes/mflix/movies/id-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const routes: RouteOptions[] = [
method: HttpMethods.GET,
url,
schema: {
tags,
tags: [...tags, 'Cache'],
params: FetchMovieRequestSchema.properties.params,
response: {
200: FetchMovieResponseSchema.properties.body
Expand Down
4 changes: 3 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { join } from 'node:path';
import fastify, { type FastifyInstance, type FastifyServerOptions } from 'fastify';
import Autoload, { type AutoloadPluginOptions } from '@fastify/autoload';
import fastifyCaching from '@fastify/caching';

const serverOptions: FastifyServerOptions = {
caseSensitive: false,
Expand All @@ -23,7 +24,8 @@ const fastifyApp: FastifyInstance = fastify(serverOptions);

Promise.all([
fastifyApp.register(Autoload, autoloadPluginsOptions),
fastifyApp.register(Autoload, autoloadRoutesOptions)
fastifyApp.register(Autoload, autoloadRoutesOptions),
fastifyApp.register(fastifyCaching, {})
])
.then(() => {
fastifyApp.listen({ host: '0.0.0.0', port: fastifyApp.config.APP_PORT }).catch((err) => {
Expand Down
6 changes: 6 additions & 0 deletions src/utils/cache-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { FastifyRequest } from 'fastify';

export function genCacheKey(request: FastifyRequest) {
const { method, url, params, body } = request;
return JSON.stringify({ method, url, params, body });
}

0 comments on commit be7ce40

Please sign in to comment.