txtdot/src/app.ts

54 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-08-13 20:38:33 +03:00
import { IConfigService } from "./config/config.interface";
import { ConfigService } from "./config/config.service";
2023-08-14 13:42:13 +03:00
2023-08-13 20:38:33 +03:00
import NodeCache from "node-cache";
2023-08-14 13:05:34 +03:00
import Fastify from "fastify";
2023-08-14 13:03:19 +03:00
import middie from "@fastify/middie";
2023-08-14 13:51:46 +03:00
import { Cached } from "./types/requests";
import getRoute from "./routes/getRoute";
import parseRoute from "./routes/parseRoute";
2023-08-13 20:38:33 +03:00
class App {
config: IConfigService;
cache: NodeCache;
2023-08-14 13:42:13 +03:00
2023-08-13 20:38:33 +03:00
constructor() {
this.config = new ConfigService();
this.cache = new NodeCache({ stdTTL: 100, checkperiod: 120 });
}
2023-08-14 13:42:13 +03:00
2023-08-14 13:03:19 +03:00
async init() {
const fastify = Fastify({
logger: true,
});
2023-08-13 20:38:33 +03:00
2023-08-14 13:03:19 +03:00
await fastify.register(middie);
fastify.use((req, res, next) => {
const url = req.originalUrl || req.url || "/";
2023-08-13 20:38:33 +03:00
2023-08-14 13:42:13 +03:00
if (req.query.purge) {
2023-08-13 20:38:33 +03:00
this.cache.del(url);
next();
}
2023-08-14 13:03:19 +03:00
const cached: Cached | undefined = this.cache.get(url);
2023-08-13 20:38:33 +03:00
if (cached) {
2023-08-14 13:03:19 +03:00
res.setHeader("content-type", `${cached.contentType}; charset=utf-8`);
res.end(cached.content);
2023-08-13 20:38:33 +03:00
} else {
next();
}
});
2023-08-14 13:51:46 +03:00
fastify.register(getRoute(this.cache));
fastify.register(parseRoute(this.cache));
2023-08-13 21:39:23 +03:00
2023-08-14 13:03:19 +03:00
fastify.listen({ port: Number(this.config.get("PORT")) }, () => {
2023-08-13 20:38:33 +03:00
console.log(`Listening on port ${this.config.get("PORT")}`);
});
}
}
const app = new App();
app.init();