From f8e0d0e4c96607860d913632ade7f01e11bed5d7 Mon Sep 17 00:00:00 2001 From: Vadim Date: Tue, 1 Dec 2026 10:18:55 +0000 Subject: [PATCH 1/4] Support multiple templates under /templates/:templateId db.json now holds { templates, sentEmails }. Each template has its own tree and its own library of elements; node and element keys are unique within a template. The old single recipeTemplate is migrated on load into one template named "Default template" (options become elements). New: GET/POST /templates, GET/PATCH/DELETE /templates/:templateId. Tree, elements and generate move under /templates/:templateId; the old /tree, /elements and /generate routes are removed. Unknown templates return 404 NOT_FOUND, every change bumps the template's updatedAt, and generate writes public/generated/.html (removed together with the template). Breaking change: version 3.0.0. --- openapi.json | 435 +++++++++++++++++- package-lock.json | 4 +- package.json | 2 +- src/modules/elements/elements.controller.ts | 22 +- src/modules/elements/elements.router.ts | 9 +- src/modules/elements/elements.schemas.ts | 4 +- src/modules/elements/elements.service.ts | 31 +- src/modules/generate/generate.controller.ts | 5 +- src/modules/generate/generate.router.ts | 7 +- src/modules/generate/generate.service.ts | 40 +- src/modules/templates/templates.controller.ts | 35 ++ src/modules/templates/templates.helpers.ts | 19 + src/modules/templates/templates.router.ts | 24 + src/modules/templates/templates.schemas.ts | 36 ++ src/modules/templates/templates.service.ts | 61 +++ src/modules/tree/tree.controller.ts | 25 +- src/modules/tree/tree.router.ts | 11 +- src/modules/tree/tree.schemas.ts | 4 +- src/modules/tree/tree.service.ts | 36 +- src/openapi.ts | 114 +++-- src/routes.ts | 20 +- src/storage/db.types.ts | 35 +- src/storage/json-file-store.test.ts | 104 ++++- src/storage/json-file-store.ts | 70 ++- test/app.test.ts | 315 +++++++++++-- test/openapi.test.ts | 7 +- 26 files changed, 1253 insertions(+), 222 deletions(-) create mode 100644 src/modules/templates/templates.controller.ts create mode 100644 src/modules/templates/templates.helpers.ts create mode 100644 src/modules/templates/templates.router.ts create mode 100644 src/modules/templates/templates.schemas.ts create mode 100644 src/modules/templates/templates.service.ts diff --git a/openapi.json b/openapi.json index 0874792..e7e860e 100644 --- a/openapi.json +++ b/openapi.json @@ -2,8 +2,8 @@ "openapi": "3.1.0", "info": { "title": "Email template editor API", - "version": "2.0.0", - "description": "Stores the template tree and the library of reusable elements, and renders the tree into one HTML email. Errors always have the ErrorResponse shape." + "version": "3.0.0", + "description": "Stores email templates (each with its own tree and library of reusable elements) and renders a tree into one HTML email. Errors always have the ErrorResponse shape." }, "servers": [ { @@ -39,9 +39,201 @@ } } }, - "/tree": { + "/templates": { "get": { - "summary": "Get the whole template tree", + "summary": "List templates, most recently changed first", + "responses": { + "200": { + "description": "Template summaries", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TemplateSummary" + } + } + } + } + } + } + }, + "post": { + "summary": "Create an empty template", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateTemplateBody" + } + } + } + }, + "responses": { + "201": { + "description": "The new template", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TemplateSummary" + } + } + } + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "413": { + "description": "Body too large (PAYLOAD_TOO_LARGE)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, + "/templates/{templateId}": { + "parameters": [ + { + "name": "templateId", + "in": "path", + "required": true, + "description": "Template id", + "schema": { + "type": "string", + "pattern": "^[\\w-]{1,128}$" + } + } + ], + "get": { + "summary": "Get a template's name and timestamps", + "responses": { + "200": { + "description": "Template summary", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TemplateSummary" + } + } + } + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + }, + "patch": { + "summary": "Rename a template", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateTemplateBody" + } + } + } + }, + "responses": { + "204": { + "description": "Done" + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + }, + "delete": { + "summary": "Delete a template and its generated file", + "responses": { + "204": { + "description": "Done" + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, + "/templates/{templateId}/tree": { + "parameters": [ + { + "name": "templateId", + "in": "path", + "required": true, + "description": "Template id", + "schema": { + "type": "string", + "pattern": "^[\\w-]{1,128}$" + } + } + ], + "get": { + "summary": "Get the template's whole tree", "responses": { "200": { "description": "Root nodes", @@ -55,11 +247,31 @@ } } } + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } } } }, "put": { - "summary": "Replace the whole template tree", + "summary": "Replace the template's whole tree", "requestBody": { "required": true, "content": { @@ -84,6 +296,16 @@ } } }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, "409": { "description": "Key already exists (CONFLICT)", "content": { @@ -107,7 +329,19 @@ } } }, - "/tree/nodes": { + "/templates/{templateId}/tree/nodes": { + "parameters": [ + { + "name": "templateId", + "in": "path", + "required": true, + "description": "Template id", + "schema": { + "type": "string", + "pattern": "^[\\w-]{1,128}$" + } + } + ], "post": { "summary": "Add a node under a parent", "requestBody": { @@ -142,7 +376,7 @@ } }, "404": { - "description": "Not found (NOT_FOUND)", + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", "content": { "application/json": { "schema": { @@ -174,8 +408,18 @@ } } }, - "/tree/nodes/{key}": { + "/templates/{templateId}/tree/nodes/{key}": { "parameters": [ + { + "name": "templateId", + "in": "path", + "required": true, + "description": "Template id", + "schema": { + "type": "string", + "pattern": "^[\\w-]{1,128}$" + } + }, { "name": "key", "in": "path", @@ -214,7 +458,7 @@ } }, "404": { - "description": "Not found (NOT_FOUND)", + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", "content": { "application/json": { "schema": { @@ -231,8 +475,18 @@ "204": { "description": "Done" }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, "404": { - "description": "Not found (NOT_FOUND)", + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", "content": { "application/json": { "schema": { @@ -244,9 +498,21 @@ } } }, - "/elements": { + "/templates/{templateId}/elements": { + "parameters": [ + { + "name": "templateId", + "in": "path", + "required": true, + "description": "Template id", + "schema": { + "type": "string", + "pattern": "^[\\w-]{1,128}$" + } + } + ], "get": { - "summary": "List library elements", + "summary": "List the template's library elements", "responses": { "200": { "description": "All elements", @@ -260,6 +526,26 @@ } } } + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } } } }, @@ -296,6 +582,16 @@ } } }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, "409": { "description": "Key already exists (CONFLICT)", "content": { @@ -319,8 +615,18 @@ } } }, - "/elements/{key}": { + "/templates/{templateId}/elements/{key}": { "parameters": [ + { + "name": "templateId", + "in": "path", + "required": true, + "description": "Template id", + "schema": { + "type": "string", + "pattern": "^[\\w-]{1,128}$" + } + }, { "name": "key", "in": "path", @@ -359,7 +665,7 @@ } }, "404": { - "description": "Not found (NOT_FOUND)", + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", "content": { "application/json": { "schema": { @@ -376,8 +682,18 @@ "204": { "description": "Done" }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, "404": { - "description": "Not found (NOT_FOUND)", + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", "content": { "application/json": { "schema": { @@ -389,9 +705,21 @@ } } }, - "/generate": { + "/templates/{templateId}/generate": { + "parameters": [ + { + "name": "templateId", + "in": "path", + "required": true, + "description": "Template id", + "schema": { + "type": "string", + "pattern": "^[\\w-]{1,128}$" + } + } + ], "post": { - "summary": "Render the tree into an HTML file and return its URL", + "summary": "Render the tree into .html and return its URL", "responses": { "200": { "description": "Link to the generated file", @@ -403,6 +731,26 @@ } } }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND): the template, or the key or id in the path", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, "422": { "description": "Template tree is empty (TREE_EMPTY)", "content": { @@ -419,6 +767,59 @@ }, "components": { "schemas": { + "TemplateSummary": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time", + "description": "ISO 8601 timestamp" + }, + "updatedAt": { + "type": "string", + "format": "date-time", + "description": "ISO 8601 timestamp" + } + }, + "required": [ + "id", + "name", + "createdAt", + "updatedAt" + ] + }, + "CreateTemplateBody": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "name" + ] + }, + "UpdateTemplateBody": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "name" + ] + }, "TreeNode": { "type": "object", "properties": { diff --git a/package-lock.json b/package-lock.json index 5c505c1..eac9513 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "email-template-editor-nodejs", - "version": "2.0.0", + "version": "3.0.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "email-template-editor-nodejs", - "version": "2.0.0", + "version": "3.0.0", "license": "ISC", "dependencies": { "cors": "^2.8.6", diff --git a/package.json b/package.json index 658b5a2..1d6744f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "email-template-editor-nodejs", - "version": "2.0.0", + "version": "3.0.0", "description": "REST API for the LLazyEmail email template editor", "private": true, "type": "module", diff --git a/src/modules/elements/elements.controller.ts b/src/modules/elements/elements.controller.ts index 1a605ba..fbe6e78 100644 --- a/src/modules/elements/elements.controller.ts +++ b/src/modules/elements/elements.controller.ts @@ -1,25 +1,29 @@ import type { Request, Response } from "express"; -import type { CreateElementBody, UpdateElementBody } from "./elements.schemas.js"; +import type { TemplateParams } from "../templates/templates.schemas.js"; +import type { CreateElementBody, ElementParams, UpdateElementBody } from "./elements.schemas.js"; import type { ElementsService } from "./elements.service.js"; export class ElementsController { constructor(private readonly service: ElementsService) {} - list = async (_req: Request, res: Response): Promise => { - res.json(await this.service.list()); + list = async (req: Request, res: Response): Promise => { + res.json(await this.service.list(req.params.templateId)); }; - create = async (req: Request, res: Response): Promise => { - res.status(201).json(await this.service.create(req.body as CreateElementBody)); + create = async (req: Request, res: Response): Promise => { + const element = req.body as CreateElementBody; + res.status(201).json(await this.service.create(req.params.templateId, element)); }; - update = async (req: Request<{ key: string }>, res: Response): Promise => { - await this.service.update(req.params.key, req.body as UpdateElementBody); + update = async (req: Request, res: Response): Promise => { + const { templateId, key } = req.params; + await this.service.update(templateId, key, req.body as UpdateElementBody); res.status(204).end(); }; - remove = async (req: Request<{ key: string }>, res: Response): Promise => { - await this.service.remove(req.params.key); + remove = async (req: Request, res: Response): Promise => { + const { templateId, key } = req.params; + await this.service.remove(templateId, key); res.status(204).end(); }; } diff --git a/src/modules/elements/elements.router.ts b/src/modules/elements/elements.router.ts index 1f31346..6975d37 100644 --- a/src/modules/elements/elements.router.ts +++ b/src/modules/elements/elements.router.ts @@ -1,5 +1,6 @@ import { Router } from "express"; import { validate } from "../../common/middleware/validate.js"; +import { templateParamsSchema } from "../templates/templates.schemas.js"; import type { ElementsController } from "./elements.controller.js"; import { createElementBodySchema, @@ -7,11 +8,13 @@ import { updateElementBodySchema, } from "./elements.schemas.js"; +/** Mounted at /templates/:templateId/elements. */ export function createElementsRouter(controller: ElementsController): Router { - const router = Router(); + const router = Router({ mergeParams: true }); + const params = templateParamsSchema; - router.get("/", controller.list); - router.post("/", validate({ body: createElementBodySchema }), controller.create); + router.get("/", validate({ params }), controller.list); + router.post("/", validate({ params, body: createElementBodySchema }), controller.create); router.patch( "/:key", validate({ params: elementParamsSchema, body: updateElementBodySchema }), diff --git a/src/modules/elements/elements.schemas.ts b/src/modules/elements/elements.schemas.ts index b7c6206..c4b8830 100644 --- a/src/modules/elements/elements.schemas.ts +++ b/src/modules/elements/elements.schemas.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { templateParamsSchema } from "../templates/templates.schemas.js"; export const elementKeySchema = z.string().trim().min(1, "key must not be empty"); @@ -17,7 +18,8 @@ export const updateElementBodySchema = z message: "At least one of title or value is required", }); -export const elementParamsSchema = z.object({ key: elementKeySchema }); +export const elementParamsSchema = templateParamsSchema.extend({ key: elementKeySchema }); export type CreateElementBody = z.infer; export type UpdateElementBody = z.infer; +export type ElementParams = z.infer; diff --git a/src/modules/elements/elements.service.ts b/src/modules/elements/elements.service.ts index fb06dbe..7c492da 100644 --- a/src/modules/elements/elements.service.ts +++ b/src/modules/elements/elements.service.ts @@ -1,42 +1,47 @@ import { ConflictError, NotFoundError } from "../../common/errors.js"; import type { Element } from "../../storage/db.types.js"; import type { TemplateStore } from "../../storage/template-store.js"; +import { findTemplate, touch } from "../templates/templates.helpers.js"; import type { UpdateElementBody } from "./elements.schemas.js"; +/** The library of reusable elements of one template. Keys are unique within a template. */ export class ElementsService { constructor(private readonly store: TemplateStore) {} - async list(): Promise { - const data = await this.store.read(); - return data.recipeTemplate.options; + async list(templateId: string): Promise { + return findTemplate(await this.store.read(), templateId).elements; } - async create(element: Element): Promise { + async create(templateId: string, element: Element): Promise { await this.store.update((data) => { - const { options } = data.recipeTemplate; - if (options.some((item) => item.key === element.key)) { + const template = findTemplate(data, templateId); + if (template.elements.some((item) => item.key === element.key)) { throw new ConflictError(`Element with key "${element.key}" already exists`); } - options.push(element); + template.elements.push(element); + touch(template); }); return element; } - async update(key: string, patch: UpdateElementBody): Promise { + async update(templateId: string, key: string, patch: UpdateElementBody): Promise { await this.store.update((data) => { - const element = data.recipeTemplate.options.find((item) => item.key === key); + const template = findTemplate(data, templateId); + const element = template.elements.find((item) => item.key === key); if (!element) throw new NotFoundError(`Element with key "${key}" not found`); if (patch.title !== undefined) element.title = patch.title; if (patch.value !== undefined) element.value = patch.value; + touch(template); }); } - async remove(key: string): Promise { + async remove(templateId: string, key: string): Promise { await this.store.update((data) => { - const { options } = data.recipeTemplate; - const index = options.findIndex((item) => item.key === key); + const template = findTemplate(data, templateId); + const index = template.elements.findIndex((item) => item.key === key); if (index === -1) throw new NotFoundError(`Element with key "${key}" not found`); - options.splice(index, 1); + template.elements.splice(index, 1); + touch(template); }); } } diff --git a/src/modules/generate/generate.controller.ts b/src/modules/generate/generate.controller.ts index d9d11e5..eeb01f5 100644 --- a/src/modules/generate/generate.controller.ts +++ b/src/modules/generate/generate.controller.ts @@ -1,11 +1,12 @@ import type { Request, Response } from "express"; +import type { TemplateParams } from "../templates/templates.schemas.js"; import type { GenerateService } from "./generate.service.js"; export class GenerateController { constructor(private readonly service: GenerateService) {} - generate = async (req: Request, res: Response): Promise => { - const { publicPath } = await this.service.generate(); + generate = async (req: Request, res: Response): Promise => { + const { publicPath } = await this.service.generate(req.params.templateId); res.json({ url: `${req.protocol}://${req.get("host")}${publicPath}` }); }; } diff --git a/src/modules/generate/generate.router.ts b/src/modules/generate/generate.router.ts index b24f662..28beada 100644 --- a/src/modules/generate/generate.router.ts +++ b/src/modules/generate/generate.router.ts @@ -1,8 +1,11 @@ import { Router } from "express"; +import { validate } from "../../common/middleware/validate.js"; +import { templateParamsSchema } from "../templates/templates.schemas.js"; import type { GenerateController } from "./generate.controller.js"; +/** Mounted at /templates/:templateId/generate. */ export function createGenerateRouter(controller: GenerateController): Router { - const router = Router(); - router.post("/", controller.generate); + const router = Router({ mergeParams: true }); + router.post("/", validate({ params: templateParamsSchema }), controller.generate); return router; } diff --git a/src/modules/generate/generate.service.ts b/src/modules/generate/generate.service.ts index 9046210..d79b7aa 100644 --- a/src/modules/generate/generate.service.ts +++ b/src/modules/generate/generate.service.ts @@ -2,10 +2,30 @@ import { randomUUID } from "node:crypto"; import { mkdir, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { AppError } from "../../common/errors.js"; +import type { TreeNode } from "../../storage/db.types.js"; import type { TemplateStore } from "../../storage/template-store.js"; +import { findTemplate } from "../templates/templates.helpers.js"; import { generateHtml } from "./generate-html.js"; -export const GENERATED_FILE_NAME = "nmtgTemplate.html"; +const GENERATED_DIR = "generated"; + +/** URL path of a template's generated HTML file (served from the public directory). */ +export function generatedPublicPath(templateId: string): string { + return `/${GENERATED_DIR}/${encodeURIComponent(templateId)}.html`; +} + +/** File system path of a template's generated HTML file. `templateId` is validated by the router. */ +export function generatedFilePath(publicDir: string, templateId: string): string { + return path.join(publicDir, GENERATED_DIR, `${path.basename(templateId)}.html`); +} + +/** Renders a template tree, or fails with 422 TREE_EMPTY when there is nothing to render. */ +export function renderTree(tree: TreeNode[]): string { + if (tree.length === 0) { + throw new AppError(422, "TREE_EMPTY", "Template tree is empty, add a root element first"); + } + return generateHtml(tree); +} export class GenerateService { constructor( @@ -13,22 +33,16 @@ export class GenerateService { private readonly publicDir: string, ) {} - /** Renders the current tree to `/generated/` and returns its public path. */ - async generate(): Promise<{ publicPath: string }> { - const { tree } = (await this.store.read()).recipeTemplate; - if (tree.length === 0) { - throw new AppError(422, "TREE_EMPTY", "Template tree is empty, add a root element first"); - } - - const html = generateHtml(tree); - const dir = path.join(this.publicDir, "generated"); - const target = path.join(dir, GENERATED_FILE_NAME); + /** Renders the template's tree to `/generated/.html`; returns its public path. */ + async generate(templateId: string): Promise<{ publicPath: string }> { + const html = renderTree(findTemplate(await this.store.read(), templateId).tree); + const target = generatedFilePath(this.publicDir, templateId); const tmp = `${target}.${randomUUID()}.tmp`; - await mkdir(dir, { recursive: true }); + await mkdir(path.dirname(target), { recursive: true }); await writeFile(tmp, html); await rename(tmp, target); - return { publicPath: `/generated/${GENERATED_FILE_NAME}` }; + return { publicPath: generatedPublicPath(templateId) }; } } diff --git a/src/modules/templates/templates.controller.ts b/src/modules/templates/templates.controller.ts new file mode 100644 index 0000000..41ae876 --- /dev/null +++ b/src/modules/templates/templates.controller.ts @@ -0,0 +1,35 @@ +import type { Request, Response } from "express"; +import type { + CreateTemplateBody, + TemplateParams, + UpdateTemplateBody, +} from "./templates.schemas.js"; +import type { TemplatesService } from "./templates.service.js"; + +export class TemplatesController { + constructor(private readonly service: TemplatesService) {} + + list = async (_req: Request, res: Response): Promise => { + res.json(await this.service.list()); + }; + + create = async (req: Request, res: Response): Promise => { + const { name } = req.body as CreateTemplateBody; + res.status(201).json(await this.service.create(name)); + }; + + get = async (req: Request, res: Response): Promise => { + res.json(await this.service.get(req.params.templateId)); + }; + + rename = async (req: Request, res: Response): Promise => { + const { name } = req.body as UpdateTemplateBody; + await this.service.rename(req.params.templateId, name); + res.status(204).end(); + }; + + remove = async (req: Request, res: Response): Promise => { + await this.service.delete(req.params.templateId); + res.status(204).end(); + }; +} diff --git a/src/modules/templates/templates.helpers.ts b/src/modules/templates/templates.helpers.ts new file mode 100644 index 0000000..a3cc8c1 --- /dev/null +++ b/src/modules/templates/templates.helpers.ts @@ -0,0 +1,19 @@ +import { NotFoundError } from "../../common/errors.js"; +import type { DbData, Template } from "../../storage/db.types.js"; +import type { TemplateSummary } from "./templates.schemas.js"; + +/** Returns the template with `id`, or throws NOT_FOUND. Shared by every template-scoped module. */ +export function findTemplate(data: DbData, id: string): Template { + const template = data.templates.find((item) => item.id === id); + if (!template) throw new NotFoundError(`Template "${id}" not found`); + return template; +} + +/** Marks the template as changed; call from every mutation of its name, tree or elements. */ +export function touch(template: Template): void { + template.updatedAt = new Date().toISOString(); +} + +export function toSummary({ id, name, createdAt, updatedAt }: Template): TemplateSummary { + return { id, name, createdAt, updatedAt }; +} diff --git a/src/modules/templates/templates.router.ts b/src/modules/templates/templates.router.ts new file mode 100644 index 0000000..dd1517f --- /dev/null +++ b/src/modules/templates/templates.router.ts @@ -0,0 +1,24 @@ +import { Router } from "express"; +import { validate } from "../../common/middleware/validate.js"; +import type { TemplatesController } from "./templates.controller.js"; +import { + createTemplateBodySchema, + templateParamsSchema, + updateTemplateBodySchema, +} from "./templates.schemas.js"; + +export function createTemplatesRouter(controller: TemplatesController): Router { + const router = Router(); + + router.get("/", controller.list); + router.post("/", validate({ body: createTemplateBodySchema }), controller.create); + router.get("/:templateId", validate({ params: templateParamsSchema }), controller.get); + router.patch( + "/:templateId", + validate({ params: templateParamsSchema, body: updateTemplateBodySchema }), + controller.rename, + ); + router.delete("/:templateId", validate({ params: templateParamsSchema }), controller.remove); + + return router; +} diff --git a/src/modules/templates/templates.schemas.ts b/src/modules/templates/templates.schemas.ts new file mode 100644 index 0000000..560e1bc --- /dev/null +++ b/src/modules/templates/templates.schemas.ts @@ -0,0 +1,36 @@ +import { z } from "zod"; + +/** + * Template ids are generated by the server (UUIDs). The id also names the generated HTML file, + * so only URL- and file-safe characters are accepted. + */ +export const TEMPLATE_ID_PATTERN = /^[\w-]{1,128}$/; + +export const templateIdSchema = z + .string() + .regex(TEMPLATE_ID_PATTERN, "templateId must be 1-128 letters, digits, '_' or '-'"); + +export const templateParamsSchema = z.object({ templateId: templateIdSchema }); + +const templateNameSchema = z.string().trim().min(1, "name must not be empty").max(200); + +export const createTemplateBodySchema = z.object({ name: templateNameSchema }); + +export const updateTemplateBodySchema = z.object({ name: templateNameSchema }); + +/** Response field: an ISO 8601 timestamp written by the server. */ +export const timestampSchema = z + .string() + .meta({ format: "date-time", description: "ISO 8601 timestamp" }); + +export const templateSummarySchema = z.object({ + id: z.string(), + name: z.string(), + createdAt: timestampSchema, + updatedAt: timestampSchema, +}); + +export type TemplateParams = z.infer; +export type CreateTemplateBody = z.infer; +export type UpdateTemplateBody = z.infer; +export type TemplateSummary = z.infer; diff --git a/src/modules/templates/templates.service.ts b/src/modules/templates/templates.service.ts new file mode 100644 index 0000000..13132d6 --- /dev/null +++ b/src/modules/templates/templates.service.ts @@ -0,0 +1,61 @@ +import { randomUUID } from "node:crypto"; +import { rm } from "node:fs/promises"; +import type { Template } from "../../storage/db.types.js"; +import type { TemplateStore } from "../../storage/template-store.js"; +import { generatedFilePath } from "../generate/generate.service.js"; +import { findTemplate, toSummary, touch } from "./templates.helpers.js"; +import type { TemplateSummary } from "./templates.schemas.js"; + +export class TemplatesService { + constructor( + private readonly store: TemplateStore, + private readonly publicDir: string, + ) {} + + /** Summaries (no tree or elements), most recently changed first. */ + async list(): Promise { + const { templates } = await this.store.read(); + // Reverse first so that, with equal timestamps, the later-created template comes first. + return [...templates] + .reverse() + .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)) + .map(toSummary); + } + + async create(name: string): Promise { + const now = new Date().toISOString(); + const template: Template = { + id: randomUUID(), + name, + tree: [], + elements: [], + createdAt: now, + updatedAt: now, + }; + await this.store.update((data) => { + data.templates.push(template); + }); + return toSummary(template); + } + + async get(id: string): Promise { + return toSummary(findTemplate(await this.store.read(), id)); + } + + async rename(id: string, name: string): Promise { + await this.store.update((data) => { + const template = findTemplate(data, id); + template.name = name; + touch(template); + }); + } + + /** Deletes the template and its generated HTML file. Sent-email log entries are kept. */ + async delete(id: string): Promise { + await this.store.update((data) => { + const template = findTemplate(data, id); + data.templates.splice(data.templates.indexOf(template), 1); + }); + await rm(generatedFilePath(this.publicDir, id), { force: true }); + } +} diff --git a/src/modules/tree/tree.controller.ts b/src/modules/tree/tree.controller.ts index d60889c..e529581 100644 --- a/src/modules/tree/tree.controller.ts +++ b/src/modules/tree/tree.controller.ts @@ -1,33 +1,36 @@ import type { Request, Response } from "express"; -import type { AddNodeBody, SaveTreeBody, UpdateNodeBody } from "./tree.schemas.js"; +import type { TemplateParams } from "../templates/templates.schemas.js"; +import type { AddNodeBody, NodeParams, SaveTreeBody, UpdateNodeBody } from "./tree.schemas.js"; import type { TreeService } from "./tree.service.js"; /** HTTP adapter: maps requests to TreeService calls. Input is already validated by the router. */ export class TreeController { constructor(private readonly service: TreeService) {} - getTree = async (_req: Request, res: Response): Promise => { - res.json(await this.service.getTree()); + getTree = async (req: Request, res: Response): Promise => { + res.json(await this.service.getTree(req.params.templateId)); }; - replaceTree = async (req: Request, res: Response): Promise => { + replaceTree = async (req: Request, res: Response): Promise => { const { treeData } = req.body as SaveTreeBody; - await this.service.replaceTree(treeData); + await this.service.replaceTree(req.params.templateId, treeData); res.status(204).end(); }; - addNode = async (req: Request, res: Response): Promise => { + addNode = async (req: Request, res: Response): Promise => { const { parentKey, item } = req.body as AddNodeBody; - res.status(201).json(await this.service.addNode(parentKey, item)); + res.status(201).json(await this.service.addNode(req.params.templateId, parentKey, item)); }; - updateNode = async (req: Request<{ key: string }>, res: Response): Promise => { - await this.service.updateNode(req.params.key, req.body as UpdateNodeBody); + updateNode = async (req: Request, res: Response): Promise => { + const { templateId, key } = req.params; + await this.service.updateNode(templateId, key, req.body as UpdateNodeBody); res.status(204).end(); }; - deleteNode = async (req: Request<{ key: string }>, res: Response): Promise => { - await this.service.deleteNode(req.params.key); + deleteNode = async (req: Request, res: Response): Promise => { + const { templateId, key } = req.params; + await this.service.deleteNode(templateId, key); res.status(204).end(); }; } diff --git a/src/modules/tree/tree.router.ts b/src/modules/tree/tree.router.ts index ee6447d..4f8afbf 100644 --- a/src/modules/tree/tree.router.ts +++ b/src/modules/tree/tree.router.ts @@ -1,5 +1,6 @@ import { Router } from "express"; import { validate } from "../../common/middleware/validate.js"; +import { templateParamsSchema } from "../templates/templates.schemas.js"; import type { TreeController } from "./tree.controller.js"; import { addNodeBodySchema, @@ -8,12 +9,14 @@ import { updateNodeBodySchema, } from "./tree.schemas.js"; +/** Mounted at /templates/:templateId/tree. */ export function createTreeRouter(controller: TreeController): Router { - const router = Router(); + const router = Router({ mergeParams: true }); + const params = templateParamsSchema; - router.get("/", controller.getTree); - router.put("/", validate({ body: saveTreeBodySchema }), controller.replaceTree); - router.post("/nodes", validate({ body: addNodeBodySchema }), controller.addNode); + router.get("/", validate({ params }), controller.getTree); + router.put("/", validate({ params, body: saveTreeBodySchema }), controller.replaceTree); + router.post("/nodes", validate({ params, body: addNodeBodySchema }), controller.addNode); router.patch( "/nodes/:key", validate({ params: nodeParamsSchema, body: updateNodeBodySchema }), diff --git a/src/modules/tree/tree.schemas.ts b/src/modules/tree/tree.schemas.ts index 6245ab0..1d1d459 100644 --- a/src/modules/tree/tree.schemas.ts +++ b/src/modules/tree/tree.schemas.ts @@ -1,5 +1,6 @@ import { z } from "zod"; import type { TreeNode } from "../../storage/db.types.js"; +import { templateParamsSchema } from "../templates/templates.schemas.js"; export const nodeKeySchema = z.string().trim().min(1, "key must not be empty"); @@ -31,8 +32,9 @@ export const updateNodeBodySchema = z message: "At least one of title or value is required", }); -export const nodeParamsSchema = z.object({ key: nodeKeySchema }); +export const nodeParamsSchema = templateParamsSchema.extend({ key: nodeKeySchema }); export type SaveTreeBody = z.infer; export type AddNodeBody = z.infer; export type UpdateNodeBody = z.infer; +export type NodeParams = z.infer; diff --git a/src/modules/tree/tree.service.ts b/src/modules/tree/tree.service.ts index cf6b826..f048dff 100644 --- a/src/modules/tree/tree.service.ts +++ b/src/modules/tree/tree.service.ts @@ -1,53 +1,61 @@ import { ConflictError, NotFoundError } from "../../common/errors.js"; import type { TreeNode } from "../../storage/db.types.js"; import type { TemplateStore } from "../../storage/template-store.js"; +import { findTemplate, touch } from "../templates/templates.helpers.js"; import { addNode, collectKeys, deleteNode, updateNode } from "./tree.helpers.js"; import type { UpdateNodeBody } from "./tree.schemas.js"; +/** The tree of one template. Node keys are unique within a template. */ export class TreeService { constructor(private readonly store: TemplateStore) {} - async getTree(): Promise { - const data = await this.store.read(); - return data.recipeTemplate.tree; + async getTree(templateId: string): Promise { + return findTemplate(await this.store.read(), templateId).tree; } - async replaceTree(tree: TreeNode[]): Promise { - assertUniqueKeys(tree); + async replaceTree(templateId: string, tree: TreeNode[]): Promise { await this.store.update((data) => { - data.recipeTemplate.tree = tree; + const template = findTemplate(data, templateId); + assertUniqueKeys(tree); + template.tree = tree; + touch(template); }); } - async addNode(parentKey: string, item: TreeNode): Promise { + async addNode(templateId: string, parentKey: string, item: TreeNode): Promise { await this.store.update((data) => { - const { tree } = data.recipeTemplate; - const existing = new Set(collectKeys(tree)); + const template = findTemplate(data, templateId); + const existing = new Set(collectKeys(template.tree)); const clash = collectKeys([item]).find((key) => existing.has(key)); if (clash !== undefined) { throw new ConflictError(`Tree node with key "${clash}" already exists`); } assertUniqueKeys([item]); - if (!addNode(tree, parentKey, item)) { + if (!addNode(template.tree, parentKey, item)) { throw new NotFoundError(`Parent tree node "${parentKey}" not found`); } + touch(template); }); return item; } - async updateNode(key: string, patch: UpdateNodeBody): Promise { + async updateNode(templateId: string, key: string, patch: UpdateNodeBody): Promise { await this.store.update((data) => { - if (!updateNode(data.recipeTemplate.tree, key, patch)) { + const template = findTemplate(data, templateId); + if (!updateNode(template.tree, key, patch)) { throw new NotFoundError(`Tree node "${key}" not found`); } + touch(template); }); } - async deleteNode(key: string): Promise { + async deleteNode(templateId: string, key: string): Promise { await this.store.update((data) => { - if (!deleteNode(data.recipeTemplate.tree, key)) { + const template = findTemplate(data, templateId); + if (!deleteNode(template.tree, key)) { throw new NotFoundError(`Tree node "${key}" not found`); } + touch(template); }); } } diff --git a/src/openapi.ts b/src/openapi.ts index 7332f0f..7516c00 100644 --- a/src/openapi.ts +++ b/src/openapi.ts @@ -3,6 +3,12 @@ import { createElementBodySchema, updateElementBodySchema, } from "./modules/elements/elements.schemas.js"; +import { + TEMPLATE_ID_PATTERN, + createTemplateBodySchema, + templateSummarySchema, + updateTemplateBodySchema, +} from "./modules/templates/templates.schemas.js"; import { addNodeBodySchema, saveTreeBodySchema, @@ -35,6 +41,9 @@ const healthSchema = z.object({ status: z.literal("ok") }); /** Named schemas; each becomes #/components/schemas/. */ const components = { + TemplateSummary: templateSummarySchema, + CreateTemplateBody: createTemplateBodySchema, + UpdateTemplateBody: updateTemplateBodySchema, TreeNode: treeNodeSchema, Element: elementSchema, SaveTreeBody: saveTreeBodySchema, @@ -54,7 +63,7 @@ const json = (schema: object) => ({ content: { "application/json": { schema } } const ERROR_TEXT = { 400: "Invalid request (VALIDATION_ERROR, INVALID_JSON)", - 404: "Not found (NOT_FOUND)", + 404: "Not found (NOT_FOUND): the template, or the key or id in the path", 409: "Key already exists (CONFLICT)", 413: "Body too large (PAYLOAD_TOO_LARGE)", 422: "Template tree is empty (TREE_EMPTY)", @@ -71,13 +80,19 @@ const errors = (...statuses: (keyof typeof ERROR_TEXT)[]) => const body = (name: SchemaName) => ({ required: true, ...json(ref(name)) }); const noContent = { "204": { description: "Done" } }; -const keyParam = (what: string) => ({ - name: "key", +const pathParam = (name: string, description: string, schema: object) => ({ + name, in: "path", required: true, - description: `${what} key, URL-encoded`, - schema: { type: "string", minLength: 1 }, + description, + schema: { type: "string", ...schema }, +}); + +const keyParam = (what: string) => pathParam("key", `${what} key, URL-encoded`, { minLength: 1 }); +const templateIdParam = pathParam("templateId", "Template id", { + pattern: TEMPLATE_ID_PATTERN.source, }); +const arrayOf = (name: SchemaName) => ({ type: "array", items: ref(name) }); function componentSchemas(): Record { const registry = z.registry<{ id: string }>(); @@ -105,9 +120,9 @@ export function buildOpenApiDocument() { openapi: "3.1.0", info: { title: "Email template editor API", - version: "2.0.0", + version: "3.0.0", description: - "Stores the template tree and the library of reusable elements, and renders the tree into one HTML email. Errors always have the ErrorResponse shape.", + "Stores email templates (each with its own tree and library of reusable elements) and renders a tree into one HTML email. Errors always have the ErrorResponse shape.", }, servers: [{ url: "http://localhost:9000", description: "Local development" }], paths: { @@ -123,23 +138,58 @@ export function buildOpenApiDocument() { responses: { "200": { description: "OpenAPI 3.1 document" } }, }, }, - "/tree": { + "/templates": { + get: { + summary: "List templates, most recently changed first", + responses: { + "200": { description: "Template summaries", ...json(arrayOf("TemplateSummary")) }, + }, + }, + post: { + summary: "Create an empty template", + requestBody: body("CreateTemplateBody"), + responses: { + "201": { description: "The new template", ...json(ref("TemplateSummary")) }, + ...errors(400, 413), + }, + }, + }, + "/templates/{templateId}": { + parameters: [templateIdParam], + get: { + summary: "Get a template's name and timestamps", + responses: { + "200": { description: "Template summary", ...json(ref("TemplateSummary")) }, + ...errors(400, 404), + }, + }, + patch: { + summary: "Rename a template", + requestBody: body("UpdateTemplateBody"), + responses: { ...noContent, ...errors(400, 404) }, + }, + delete: { + summary: "Delete a template and its generated file", + responses: { ...noContent, ...errors(400, 404) }, + }, + }, + "/templates/{templateId}/tree": { + parameters: [templateIdParam], get: { - summary: "Get the whole template tree", + summary: "Get the template's whole tree", responses: { - "200": { - description: "Root nodes", - ...json({ type: "array", items: ref("TreeNode") }), - }, + "200": { description: "Root nodes", ...json(arrayOf("TreeNode")) }, + ...errors(400, 404), }, }, put: { - summary: "Replace the whole template tree", + summary: "Replace the template's whole tree", requestBody: body("SaveTreeBody"), - responses: { ...noContent, ...errors(400, 409, 413) }, + responses: { ...noContent, ...errors(400, 404, 409, 413) }, }, }, - "/tree/nodes": { + "/templates/{templateId}/tree/nodes": { + parameters: [templateIdParam], post: { summary: "Add a node under a parent", requestBody: body("AddNodeBody"), @@ -149,8 +199,8 @@ export function buildOpenApiDocument() { }, }, }, - "/tree/nodes/{key}": { - parameters: [keyParam("Tree node")], + "/templates/{templateId}/tree/nodes/{key}": { + parameters: [templateIdParam, keyParam("Tree node")], patch: { summary: "Change a node's title and/or value", requestBody: body("UpdateNodeBody"), @@ -158,17 +208,16 @@ export function buildOpenApiDocument() { }, delete: { summary: "Delete a node and its children", - responses: { ...noContent, ...errors(404) }, + responses: { ...noContent, ...errors(400, 404) }, }, }, - "/elements": { + "/templates/{templateId}/elements": { + parameters: [templateIdParam], get: { - summary: "List library elements", + summary: "List the template's library elements", responses: { - "200": { - description: "All elements", - ...json({ type: "array", items: ref("Element") }), - }, + "200": { description: "All elements", ...json(arrayOf("Element")) }, + ...errors(400, 404), }, }, post: { @@ -176,12 +225,12 @@ export function buildOpenApiDocument() { requestBody: body("CreateElementBody"), responses: { "201": { description: "The added element", ...json(ref("Element")) }, - ...errors(400, 409, 413), + ...errors(400, 404, 409, 413), }, }, }, - "/elements/{key}": { - parameters: [keyParam("Element")], + "/templates/{templateId}/elements/{key}": { + parameters: [templateIdParam, keyParam("Element")], patch: { summary: "Change an element's title and/or value", requestBody: body("UpdateElementBody"), @@ -189,15 +238,16 @@ export function buildOpenApiDocument() { }, delete: { summary: "Delete an element", - responses: { ...noContent, ...errors(404) }, + responses: { ...noContent, ...errors(400, 404) }, }, }, - "/generate": { + "/templates/{templateId}/generate": { + parameters: [templateIdParam], post: { - summary: "Render the tree into an HTML file and return its URL", + summary: "Render the tree into .html and return its URL", responses: { "200": { description: "Link to the generated file", ...json(ref("GenerateResponse")) }, - ...errors(422), + ...errors(400, 404, 422), }, }, }, diff --git a/src/routes.ts b/src/routes.ts index a187ab5..1441406 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -5,6 +5,9 @@ import { ElementsService } from "./modules/elements/elements.service.js"; import { GenerateController } from "./modules/generate/generate.controller.js"; import { createGenerateRouter } from "./modules/generate/generate.router.js"; import { GenerateService } from "./modules/generate/generate.service.js"; +import { TemplatesController } from "./modules/templates/templates.controller.js"; +import { createTemplatesRouter } from "./modules/templates/templates.router.js"; +import { TemplatesService } from "./modules/templates/templates.service.js"; import { TreeController } from "./modules/tree/tree.controller.js"; import { createTreeRouter } from "./modules/tree/tree.router.js"; import { TreeService } from "./modules/tree/tree.service.js"; @@ -29,10 +32,21 @@ export function createRoutes({ store, publicDir }: RouteDeps): Router { res.json(openApiDocument); }); - router.use("/tree", createTreeRouter(new TreeController(new TreeService(store)))); - router.use("/elements", createElementsRouter(new ElementsController(new ElementsService(store)))); router.use( - "/generate", + "/templates", + createTemplatesRouter(new TemplatesController(new TemplatesService(store, publicDir))), + ); + // Template-scoped routers use mergeParams and validate :templateId themselves. + router.use( + "/templates/:templateId/tree", + createTreeRouter(new TreeController(new TreeService(store))), + ); + router.use( + "/templates/:templateId/elements", + createElementsRouter(new ElementsController(new ElementsService(store))), + ); + router.use( + "/templates/:templateId/generate", createGenerateRouter(new GenerateController(new GenerateService(store, publicDir))), ); diff --git a/src/storage/db.types.ts b/src/storage/db.types.ts index 40c51a8..0b4ec81 100644 --- a/src/storage/db.types.ts +++ b/src/storage/db.types.ts @@ -11,14 +11,37 @@ export interface Element { value: string; } -/** On-disk shape of db.json (kept compatible with the previous lowdb format). */ +/** One email template: its own tree and its own library of reusable elements. */ +export interface Template { + id: string; + name: string; + tree: TreeNode[]; + elements: Element[]; + /** ISO 8601 timestamps. */ + createdAt: string; + updatedAt: string; +} + +/** A logged "send": who it was for, the subject and a snapshot of the rendered HTML. */ +export interface SentEmail { + id: string; + templateId: string; + /** Template name at the time of sending; kept after the template is deleted. */ + templateName: string; + to: string[]; + subject: string; + html: string; + /** Delivery is not configured yet, so every send is only logged. */ + status: "logged"; + createdAt: string; +} + +/** On-disk shape of db.json. */ export interface DbData { - recipeTemplate: { - tree: TreeNode[]; - options: Element[]; - }; + templates: Template[]; + sentEmails: SentEmail[]; } export function createEmptyDb(): DbData { - return { recipeTemplate: { tree: [], options: [] } }; + return { templates: [], sentEmails: [] }; } diff --git a/src/storage/json-file-store.test.ts b/src/storage/json-file-store.test.ts index 18e7275..12256c6 100644 --- a/src/storage/json-file-store.test.ts +++ b/src/storage/json-file-store.test.ts @@ -2,7 +2,21 @@ import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { JsonFileStore, StorageError } from "./json-file-store.js"; +import type { DbData, Template } from "./db.types.js"; +import { JsonFileStore, MIGRATED_TEMPLATE_NAME, StorageError } from "./json-file-store.js"; + +const template = (id: string): Template => ({ + id, + name: `Template ${id}`, + tree: [], + elements: [], + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", +}); + +const addTemplate = (id: string) => (data: DbData) => { + data.templates.push(template(id)); +}; describe("JsonFileStore", () => { let dir: string; @@ -17,27 +31,81 @@ describe("JsonFileStore", () => { await rm(dir, { recursive: true, force: true }); }); + const readFileJson = async () => JSON.parse(await readFile(file, "utf8")) as DbData; + it("init creates the file with an empty structure", async () => { await new JsonFileStore(file).init(); - expect(JSON.parse(await readFile(file, "utf8"))).toEqual({ - recipeTemplate: { tree: [], options: [] }, - }); + expect(await readFileJson()).toEqual({ templates: [], sentEmails: [] }); + }); + + it("treats an empty file as an empty database", async () => { + await writeFile(file, " \n"); + expect(await new JsonFileStore(file).read()).toEqual({ templates: [], sentEmails: [] }); }); it("fills in missing collections of an existing file", async () => { - await writeFile(file, JSON.stringify({ recipeTemplate: { tree: [] } })); + await writeFile(file, JSON.stringify({ templates: [{ id: "t1", name: "One" }] })); const data = await new JsonFileStore(file).read(); - expect(data.recipeTemplate.options).toEqual([]); + expect(data.sentEmails).toEqual([]); + expect(data.templates[0]).toMatchObject({ id: "t1", name: "One", tree: [], elements: [] }); + }); + + it("keeps unknown top-level keys", async () => { + await writeFile(file, JSON.stringify({ templates: [], sentEmails: [], extra: { a: 1 } })); + expect(await new JsonFileStore(file).read()).toMatchObject({ extra: { a: 1 } }); + }); + + describe("migration from the single-template format (recipeTemplate)", () => { + const tree = [{ key: "1", title: "root", value: "

{{a}}

", children: [] }]; + const options = [{ key: "el-1", title: "{{a}}", value: "A" }]; + + it("turns recipeTemplate into one template and drops the old key", async () => { + await writeFile(file, JSON.stringify({ recipeTemplate: { tree, options } })); + await new JsonFileStore(file).init(); + + const data = await readFileJson(); + expect(Object.keys(data).sort()).toEqual(["sentEmails", "templates"]); + expect(data.sentEmails).toEqual([]); + expect(data.templates).toHaveLength(1); + const [migrated] = data.templates; + expect(migrated).toMatchObject({ name: MIGRATED_TEMPLATE_NAME, tree, elements: options }); + expect(migrated!.id).toMatch(/^[\w-]{36}$/); + expect(migrated!.createdAt).toBe(migrated!.updatedAt); + expect(Number.isNaN(Date.parse(migrated!.createdAt))).toBe(false); + }); + + it("keeps the migrated id stable once written", async () => { + await writeFile(file, JSON.stringify({ recipeTemplate: { tree, options } })); + const store = new JsonFileStore(file); + await store.init(); + const { id } = (await store.read()).templates[0]!; + expect((await store.read()).templates[0]!.id).toBe(id); + }); + + it("fills in a partial recipeTemplate", async () => { + await writeFile(file, JSON.stringify({ recipeTemplate: { tree } })); + const data = await new JsonFileStore(file).read(); + expect(data.templates[0]).toMatchObject({ tree, elements: [] }); + }); + + it("does not migrate when templates already exist", async () => { + await writeFile( + file, + JSON.stringify({ templates: [template("t1")], recipeTemplate: { tree, options } }), + ); + const data = await new JsonFileStore(file).read(); + expect(data.templates.map((t) => t.id)).toEqual(["t1"]); + }); }); it("persists updates and returns the mutator's result", async () => { const store = new JsonFileStore(file); const result = await store.update((data) => { - data.recipeTemplate.options.push({ key: "k", title: "t", value: "v" }); + addTemplate("t1")(data); return "done"; }); expect(result).toBe("done"); - expect((await new JsonFileStore(file).read()).recipeTemplate.options).toHaveLength(1); + expect((await new JsonFileStore(file).read()).templates).toHaveLength(1); }); it("does not write anything when the mutator throws", async () => { @@ -45,33 +113,25 @@ describe("JsonFileStore", () => { await store.init(); await expect( store.update((data) => { - data.recipeTemplate.options.push({ key: "k", title: "t", value: "v" }); + addTemplate("t1")(data); throw new Error("boom"); }), ).rejects.toThrow("boom"); - expect((await store.read()).recipeTemplate.options).toEqual([]); + expect((await store.read()).templates).toEqual([]); }); it("serializes concurrent updates without losing writes", async () => { const store = new JsonFileStore(file); - await Promise.all( - Array.from({ length: 25 }, (_, i) => - store.update((data) => { - data.recipeTemplate.options.push({ key: String(i), title: "t", value: "v" }); - }), - ), - ); - expect((await store.read()).recipeTemplate.options).toHaveLength(25); + await Promise.all(Array.from({ length: 25 }, (_, i) => store.update(addTemplate(String(i))))); + expect((await store.read()).templates).toHaveLength(25); expect((await readdir(dir)).filter((name) => name.endsWith(".tmp"))).toEqual([]); }); it("keeps working after a failed update", async () => { const store = new JsonFileStore(file); await expect(store.update(() => Promise.reject(new Error("fail")))).rejects.toThrow("fail"); - await store.update((data) => { - data.recipeTemplate.options.push({ key: "k", title: "t", value: "v" }); - }); - expect((await store.read()).recipeTemplate.options).toHaveLength(1); + await store.update(addTemplate("t1")); + expect((await store.read()).templates).toHaveLength(1); }); it("raises StorageError for a corrupted file", async () => { diff --git a/src/storage/json-file-store.ts b/src/storage/json-file-store.ts index c5e3a56..1f945b1 100644 --- a/src/storage/json-file-store.ts +++ b/src/storage/json-file-store.ts @@ -1,14 +1,21 @@ import { randomUUID } from "node:crypto"; import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; -import { createEmptyDb, type DbData } from "./db.types.js"; +import { + createEmptyDb, + type DbData, + type Element, + type SentEmail, + type Template, + type TreeNode, +} from "./db.types.js"; import type { TemplateStore } from "./template-store.js"; export class StorageError extends Error { override name = "StorageError"; } -/** Stores everything in a single JSON file (same format as the previous lowdb db.json). */ +/** Stores everything in a single JSON file; older formats are migrated on load (see normalize). */ export class JsonFileStore implements TemplateStore { private queue: Promise = Promise.resolve(); @@ -69,21 +76,56 @@ export class JsonFileStore implements TemplateStore { } } -/** Fills in missing collections so older/partial files still load. */ +/** Name of the template that the single pre-v3 template (`recipeTemplate`) becomes. */ +export const MIGRATED_TEMPLATE_NAME = "Default template"; + +type Json = Record; + +const isObject = (value: unknown): value is Json => + typeof value === "object" && value !== null && !Array.isArray(value); + +const arrayOr = (value: unknown): T[] => (Array.isArray(value) ? (value as T[]) : []); + +/** + * Brings older or partial files to the current shape: + * - the pre-v3 `recipeTemplate: { tree, options }` becomes one template named "Default template" + * (its `options` become the template's `elements`) and the old key is dropped; + * - missing collections are filled in; unknown top-level keys are kept. + */ function normalize(parsed: unknown): DbData { - const empty = createEmptyDb(); - if (typeof parsed !== "object" || parsed === null) return empty; + if (!isObject(parsed)) return createEmptyDb(); + + const { recipeTemplate, ...rest } = parsed; + let templates: unknown = rest.templates; + let legacy: Json = {}; - const rt = (parsed as { recipeTemplate?: unknown }).recipeTemplate; - if (typeof rt !== "object" || rt === null || Array.isArray(rt)) return { ...parsed, ...empty }; + if (!Array.isArray(templates) && isObject(recipeTemplate)) { + const now = new Date().toISOString(); + templates = [ + { + id: randomUUID(), + name: MIGRATED_TEMPLATE_NAME, + tree: recipeTemplate.tree, + elements: recipeTemplate.options, + createdAt: now, + updatedAt: now, + }, + ]; + } else if (recipeTemplate !== undefined) { + // Not migrated (templates already exist): keep it rather than lose data silently. + legacy = { recipeTemplate }; + } - const { tree, options } = rt as Partial; return { - ...(parsed as object), - recipeTemplate: { - ...rt, - tree: Array.isArray(tree) ? tree : [], - options: Array.isArray(options) ? options : [], - }, + ...rest, + ...legacy, + templates: arrayOr(templates) + .filter(isObject) + .map((template) => ({ + ...(template as unknown as Template), + tree: arrayOr(template.tree), + elements: arrayOr(template.elements), + })), + sentEmails: arrayOr(rest.sentEmails), }; } diff --git a/test/app.test.ts b/test/app.test.ts index afb4843..96feb90 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Express } from "express"; @@ -7,11 +7,13 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { createApp } from "../src/app.js"; import { createLogger } from "../src/common/logger.js"; import { loadConfig } from "../src/config/env.js"; -import type { DbData, TreeNode } from "../src/storage/db.types.js"; +import type { DbData, Template, TreeNode } from "../src/storage/db.types.js"; import { JsonFileStore } from "../src/storage/json-file-store.js"; import type { TemplateStore } from "../src/storage/template-store.js"; const fixturesDir = path.join(import.meta.dirname, "fixtures"); +const SEED_TIME = "2026-01-01T00:00:00.000Z"; +const T1 = "/templates/t1"; let dir: string; let dbFile: string; @@ -37,16 +39,43 @@ async function readDb(): Promise { return JSON.parse(await readFile(dbFile, "utf8")) as DbData; } +type Summary = { id: string; name: string; createdAt: string; updatedAt: string }; + +async function createTemplate(name: string): Promise { + const res = await request(app).post("/templates").send({ name }).expect(201); + return res.body as Summary; +} + +/** Puts t1's updatedAt back to the seed value, to see whether the next call bumps it. */ +async function resetUpdatedAt(): Promise { + const db = await readDb(); + db.templates[0]!.updatedAt = SEED_TIME; + await writeFile(dbFile, JSON.stringify(db)); +} + +async function readTemplate(id = "t1"): Promise