Skip to content

About

No description, website, or topics provided.

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

email-template-editor-nodejs

REST API for the LLazyEmail email template editor. It stores email templates (each one a tree of template parts plus its own library of reusable elements), renders a template into a single HTML email and keeps a log of sent emails.

Stack: Node 24, TypeScript (strict), Express 5, zod, pino, Vitest + Supertest.

Quick start

npm install
cp .env.example .env   # optional, defaults work out of the box
npm run dev            # http://localhost:9000, hot reload, pretty logs
Script What it does
npm run dev Run from sources with hot reload (tsx)
npm run build Compile to dist/
npm start Run the compiled server (dist/server.js)
npm test Unit + HTTP integration tests (Vitest)
npm run typecheck tsc --noEmit
npm run lint ESLint
npm run format Prettier (format:check is used in CI)
npm run openapi Regenerate openapi.json from the schemas

Architecture

HTTP request
  → middleware: helmet → cors → request-id → pino-http → json body → static files
  → router        (src/modules/*/*.router.ts)      routes + zod validation
  → controller    (src/modules/*/*.controller.ts)  HTTP only: read req, write res
  → service       (src/modules/*/*.service.ts)     business rules, throws AppError
  → store         (src/storage/template-store.ts)  persistence interface
                   └ JsonFileStore                 db.json, atomic + serialized writes
  → not-found → error-handler                      one JSON error format for everything
src/
  server.ts            bootstrap, graceful shutdown (SIGTERM/SIGINT)
  app.ts               createApp({ config, store, logger }): middleware chain
  routes.ts            composition root: store → services → controllers → routers
  config/env.ts        environment variables, validated with zod
  common/              errors, logger, middleware (request-id, validate, not-found, error-handler)
  storage/             TemplateStore interface + JsonFileStore
  modules/
    templates/         templates CRUD + findTemplate() used by the template-scoped modules
    tree/              a template's tree CRUD
    elements/          a template's reusable elements CRUD
    generate/          tree → HTML rendering
    sent-emails/       "send" (log only, no delivery yet) and the sent-emails log
test/                  HTTP integration tests + fixtures

Dependencies are passed through constructors and wired in routes.ts, so every layer can be tested in isolation and the store can be swapped (for example for SQLite or Postgres) by implementing TemplateStore.

Configuration

Variable Default Description
PORT 9000 HTTP port
DB_FILE ./db.json JSON storage file (created if missing)
PUBLIC_DIR ./public Static files; generated templates go to <PUBLIC_DIR>/generated
CORS_ORIGIN * * or a comma-separated list of allowed origins
BODY_LIMIT 50mb Max JSON body size
LOG_LEVEL info fatal … trace, or silent
NODE_ENV development development enables pretty logs and stack traces in 500 errors

Invalid values stop the server at startup with a clear message.

API

The machine-readable contract is openapi.json (OpenAPI 3.1, generated from the zod schemas, also served at GET /openapi.json). Agents and contributors: see AGENTS.md.

Everything except /health, /openapi.json and /sent-emails belongs to one template, so paths start with /templates/:templateId.

Method Path Body Success Errors
GET /health – 200 { "status": "ok" }
GET /templates – 200 TemplateSummary[]
POST /templates { name } 201 TemplateSummary 400
GET /templates/:templateId – 200 TemplateSummary 400, 404
PATCH /templates/:templateId { name } 204 400, 404
DELETE /templates/:templateId – 204 400, 404
GET /templates/:templateId/tree – 200 TreeNode[] 400, 404
PUT /templates/:templateId/tree { treeData: TreeNode[] } 204 400, 404, 409
POST /templates/:templateId/tree/nodes { parentKey, item } 201 TreeNode 400, 404, 409
PATCH /templates/:templateId/tree/nodes/:key { title?, value? } 204 400, 404
DELETE /templates/:templateId/tree/nodes/:key – 204 400, 404
GET /templates/:templateId/elements – 200 Element[] 400, 404
POST /templates/:templateId/elements { key, title, value } 201 Element 400, 404, 409
PATCH /templates/:templateId/elements/:key { title?, value? } 204 400, 404
DELETE /templates/:templateId/elements/:key – 204 400, 404
POST /templates/:templateId/generate – 200 { "url": "http://…" } 400, 404, 422
POST /templates/:templateId/send { to: string[], subject } 201 SentEmailSummary 400, 404, 422
GET /sent-emails – 200 SentEmailSummary[]
GET /sent-emails/:id – 200 SentEmail 400, 404

All values are strings (or arrays of strings); timestamps are ISO 8601.

  • TemplateSummary is { id, name, createdAt, updatedAt }. GET /templates returns the most recently changed first; any change to a template's name, tree or elements updates updatedAt. Template names are 1–200 characters.
  • TreeNode is { key, title, value, children?: TreeNode[] } and Element is { key, title, value }. Node and element keys are unique within a template; two templates can use the same keys.
  • SentEmailSummary is { id, templateId, templateName, to, subject, status: "logged", createdAt }; SentEmail adds html.

Template ids are generated by the server ([A-Za-z0-9_-], up to 128 characters; anything else is a 400). Element and node keys in paths must be URL-encoded.

POST /templates/:templateId/generate renders the tree (each child's title placeholder inside its parent's value is replaced with the child's rendered value), writes it to <PUBLIC_DIR>/generated/<templateId>.html and returns its URL. Deleting the template deletes that file.

POST /templates/:templateId/send takes 1–50 email addresses in to and a 1–300 character subject. It does not deliver anything yet: it renders the template and stores a log entry with a snapshot of the HTML and status: "logged". GET /sent-emails lists entries newest first without the HTML; GET /sent-emails/:id includes it. Log entries stay after their template is deleted.

Errors

Every error uses the same shape. requestId matches the X-Request-Id response header and the server logs.

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request validation failed",
    "details": [
      {
        "location": "body",
        "path": "title",
        "message": "Invalid input: expected string, received undefined"
      }
    ],
    "requestId": "8d466a15-a7bb-4aa8-8a46-35eb14f97905"
  }
}
Status code
400 VALIDATION_ERROR, INVALID_JSON
404 NOT_FOUND (template, node, element, sent email or route)
409 CONFLICT (duplicate key within the template)
413 PAYLOAD_TOO_LARGE
422 TREE_EMPTY (generate or send with an empty tree)
500 INTERNAL_ERROR (details are only logged)

Migrating from v2 to v3

v3 keeps any number of templates. On first start the server converts an existing db.json from the v2 shape { recipeTemplate: { tree, options } } to { templates, sentEmails }: the old tree and elements become one template named "Default template". Get its id from GET /templates. Each template has its own elements.

v2 v3
GET /tree GET /templates/:templateId/tree
PUT /tree PUT /templates/:templateId/tree
POST /tree/nodes POST /templates/:templateId/tree/nodes
PATCH /tree/nodes/:key PATCH /templates/:templateId/tree/nodes/:key
DELETE /tree/nodes/:key DELETE /templates/:templateId/tree/nodes/:key
GET /elements GET /templates/:templateId/elements
POST /elements POST /templates/:templateId/elements
PATCH /elements/:key PATCH /templates/:templateId/elements/:key
DELETE /elements/:key DELETE /templates/:templateId/elements/:key
POST /generate POST /templates/:templateId/generate (file <templateId>.html)

New in v3: /templates CRUD, POST /templates/:templateId/send, GET /sent-emails, GET /sent-emails/:id.

Migrating from v1 routes

v1 v2
GET /template-tree GET /tree
POST /save-template-tree PUT /tree
POST /add-node-tree POST /tree/nodes
POST /update-node-tree PATCH /tree/nodes/:key
POST /delete-node-tree DELETE /tree/nodes/:key
POST /generate (returned string) POST /generate → { url }
GET /all-elements GET /elements
POST /add-element POST /elements
PUT /element PATCH /elements/:key
DELETE /delete-element/:key DELETE /elements/:key

Docker

Production image (multi-stage, non-root, healthcheck on /health):

docker build -t email-template-editor-nodejs .
docker run -d -p 9000:9000 -v email-template-data:/app/data email-template-editor-nodejs

Data lives in /app/data/db.json. Mount a volume there so it survives container re-creation. The image is seeded with the repository's db.json.

Sample data

The repository's db.json holds one template, "Default template": a complete No More To-Go "Weekly Menu" issue. The sent-emails log is empty.

  • Tree: the root HTML has three slots ({{items}}, {{items2}}, {{items3}}). Each slot holds a two-column row with two recipe cards, six recipes in total. Each card's {{link}}, {{image}}, {{title}} and {{subtitle}} are filled.
  • Elements: {{twoBlocks}} (two-column row), {{recipeCard}} (photo, title and subtitle) and {{textBlock}} (a paragraph).

Every child's title appears in its parent's HTML, and keys are unique. POST /templates/:templateId/generate renders the issue with no placeholders left over.

Development with hot reload:

docker compose up -d
docker compose logs -f

About

No description, website, or topics provided.

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages