From 870a1b203ef86e15b650c0c0191d4d6741e88de4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BAlio?= Date: Sat, 8 Jun 2024 15:40:27 -0300 Subject: [PATCH] Typescript - Add ui route --- package-lock.json | 7 +++++++ package.json | 3 ++- src/server.ts | 15 +++++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/package-lock.json b/package-lock.json index 16410ca..b0fd33b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,7 @@ "zod": "^3.23.8" }, "devDependencies": { + "@types/ejs": "^3.1.5", "@types/node": "^20.14.0", "eslint": "^8.56.0", "jest": "^29.7.0", @@ -1720,6 +1721,12 @@ "@babel/types": "^7.20.7" } }, + "node_modules/@types/ejs": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/@types/ejs/-/ejs-3.1.5.tgz", + "integrity": "sha512-nv+GSx77ZtXiJzwKdsASqi+YQ5Z7vwHsTP0JY2SiQgjGckkBRKZnk8nIM+7oUZ1VCtuTz0+By4qVR7fqzp/Dfg==", + "dev": true + }, "node_modules/@types/graceful-fs": { "version": "4.1.9", "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", diff --git a/package.json b/package.json index c9cb189..09549a9 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "author": "JĂșlio Moura", "license": "ISC", "devDependencies": { + "@types/ejs": "^3.1.5", "@types/node": "^20.14.0", "eslint": "^8.56.0", "jest": "^29.7.0", @@ -36,4 +37,4 @@ "redis": "^4.6.13", "zod": "^3.23.8" } -} \ No newline at end of file +} diff --git a/src/server.ts b/src/server.ts index b495fee..e2cec97 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,4 +1,6 @@ import Fastify from "fastify"; +import { fastifyView } from "@fastify/view"; +import ejs from "ejs"; import { z } from "zod"; import { CacheClient, createRedisClient } from "./redis.js"; import RandomDadJokesAPI from "./random-dad-jokes.api.js"; @@ -11,6 +13,12 @@ const cacheClient = new CacheClient(redisClient).getRedisClient(); const randomDadJokesAPI = new RandomDadJokesAPI(); const messageService = new MessageService(cacheClient, randomDadJokesAPI); +fastify.register(fastifyView, { + engine: { + ejs, + }, +}); + fastify.get("/", async (request, reply) => { return { hello: "world" }; }); @@ -20,6 +28,13 @@ fastify.get("/messages", async (request, reply) => { reply.code(200).send({ message }); }); +fastify.get("/ui/messages", async (request, reply) => { + const message = await messageService.getMessage(); + return reply.viewAsync("./src/ui/message.ejs", { + message, + }); +}); + fastify.post("/messages", async (request, reply) => { const message = z.object({ message: z.string(),