Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions app/lib/openapi-definition.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"openapi": "3.0.3",
"info": {
"title": "TRASER API",
"version": "1.0.0",
"description": "Metadata TRAnslation SERvice — converts health dataset metadata between schema formats (HDRUK, GWDM, SchemaOrg, CRUK) and validates metadata against those schemas."
},
"servers": [{ "url": "/", "description": "This server" }],
"tags": [
{ "name": "translate", "description": "Translate metadata between schemas" },
{ "name": "validate", "description": "Validate metadata against a schema" },
{ "name": "find", "description": "Discover which schemas match a metadata document" },
{ "name": "list", "description": "List available schemas, templates, and translation routes" },
{ "name": "get", "description": "Retrieve a schema definition, translation map, or form hydration" }
],
"components": {
"schemas": {
"ValidationError": {
"type": "object",
"properties": {
"keyword": { "type": "string", "example": "enum" },
"instancePath": { "type": "string", "example": "/summary/contactPoint/0/contactType" },
"message": { "type": "string", "example": "must be equal to one of the allowed values" },
"params": { "type": "object" },
"invalidValue": {},
"suggestion": { "type": "string", "example": "Allowed: \"primary\", \"secondary\"" },
"allowedValues": { "type": "array", "items": {} }
}
},
"ErrorMessage": {
"type": "object",
"required": ["message"],
"properties": {
"message": { "type": "string" }
}
}
}
}
}
16 changes: 14 additions & 2 deletions app/routes.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
import type { RouteConfig } from "@react-router/dev/routes";
import { type RouteConfig, route } from "@react-router/dev/routes";

export default [] satisfies RouteConfig;
export default [
route("/status", "routes/api/status.ts"),
route("/openapi.json", "routes/api/openapi.json.ts"),
route("/translate", "routes/api/translate.ts"),
route("/validate", "routes/api/validate.ts"),
route("/find", "routes/api/find.ts"),
route("/list/schemas", "routes/api/list.schemas.ts"),
route("/list/templates", "routes/api/list.templates.ts"),
route("/list/translations", "routes/api/list.translations.ts"),
route("/get/schema", "routes/api/get.schema.ts"),
route("/get/map", "routes/api/get.map.ts"),
route("/get/form_hydration", "routes/api/get.form_hydration.ts"),
] satisfies RouteConfig;
85 changes: 85 additions & 0 deletions app/routes/api/find.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/**
* @openapi
* /find:
* post:
* tags: [find]
* summary: Find schemas that match a metadata document
* description: Tests the provided metadata against all loaded schemas and returns the ones that validate successfully.
* parameters:
* - name: with_errors
* in: query
* description: Set to 1 to include validation error details for non-matching schemas.
* schema:
* type: string
* enum: ["0", "1"]
* default: "0"
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* description: The metadata document to test.
* responses:
* '200':
* description: List of schemas that matched, optionally with validation error details for misses.
* content:
* application/json:
* schema:
* type: array
* '400':
* description: Invalid request (missing or non-JSON body).
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorMessage'
*/
import { ensureLoaded, findMatchingSchemas } from "~/lib/schema.server";
import { publishMessage } from "~/lib/audit.server";
import { fieldError, invalidRequest, type FieldError } from "~/lib/errors.server";

export async function action({ request }: { request: Request }) {
await ensureLoaded();

const url = new URL(request.url);
const withErrorsRaw = url.searchParams.get("with_errors");

const errors: FieldError[] = [];

// Content-Type must be application/json — reject when the header is absent or
// any other type.
const contentType = request.headers.get("content-type");
if (!contentType || !contentType.includes("application/json")) {
errors.push(fieldError("Invalid content type. Expected JSON.", "", "body"));
}

// with_errors is optional and defaults to 0, but when present must be 0 or 1.
let withErrors = false;
if (withErrorsRaw !== null && withErrorsRaw !== "") {
if (withErrorsRaw === "0" || withErrorsRaw === "1") {
withErrors = withErrorsRaw === "1";
} else {
errors.push(fieldError("Invalid value", "with_errors", "query", withErrorsRaw));
}
}

if (errors.length > 0) {
publishMessage(
"POST",
"find",
"Failed to validate posted metadata against available schemas"
).catch(console.error);
return invalidRequest(errors);
}

let metadata: unknown;
try {
metadata = await request.json();
} catch {
return Response.json({ message: "Invalid JSON body" }, { status: 400 });
}

const result = await findMatchingSchemas(metadata, withErrors);
publishMessage("POST", "find", "Validated metadata against available schemas").catch(console.error);
return Response.json(result);
}
102 changes: 102 additions & 0 deletions app/routes/api/get.form_hydration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/**
* @openapi
* /get/form_hydration:
* get:
* tags: [get]
* summary: Fetch a hydrated form schema
* description: Applies a JSONata form-hydration template to a schema definition and returns the result. Used to build dynamic form configurations.
* parameters:
* - name: name
* in: query
* required: true
* description: Schema name to hydrate (e.g. HDRUK).
* schema:
* type: string
* example: HDRUK
* - name: version
* in: query
* description: Schema version. Falls back to the HYDRATION_MAP_VERSION env var if omitted.
* schema:
* type: string
* - name: dataTypes
* in: query
* description: Comma-separated list of data types to inject into the hydration source.
* schema:
* type: string
* example: "Genomics,Imaging"
* responses:
* '200':
* description: Hydrated form schema.
* content:
* application/json:
* schema:
* type: object
* '400':
* description: Missing parameters or hydration template not found.
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorMessage'
*/
import jsonata from "jsonata";
import { ensureLoaded, retrieveHydrationSchema } from "~/lib/schema.server";
import { getFormHydrationTemplate } from "~/lib/templates.server";
import { publishMessage } from "~/lib/audit.server";
import { fieldError, invalidParams } from "~/lib/errors.server";

export async function loader({ request }: { request: Request }) {
await ensureLoaded();

const url = new URL(request.url);
const name = url.searchParams.get("name");
const version =
url.searchParams.get("version") ?? process.env.HYDRATION_MAP_VERSION ?? "";
const dataTypes = url.searchParams.get("dataTypes") ?? "";

if (!name) {
return invalidParams("Invalid query parameters.", [
fieldError("Invalid value", "name", "query"),
]);
}

try {
const [template, source] = await Promise.all([
getFormHydrationTemplate(name, version),
retrieveHydrationSchema(name, version),
]);

if (!template || !source) {
return Response.json({ message: "Hydration template or schema not found" }, { status: 400 });
}

const src = source as Record<string, unknown>;
src.dataTypes = dataTypes.split(",");

const expression = jsonata(template);
const result = await expression.evaluate(src);

// A JSONata expression that matches nothing evaluates to `undefined`, which
// JSON.stringify turns into a malformed empty body — return a 400 instead.
if (result === undefined) {
publishMessage(
"GET",
"get/form_hydration",
`${name}-${version} failed to hydrate`
).catch(console.error);
return Response.json({ message: "Hydration failed." }, { status: 400 });
}

publishMessage("GET", "get/form_hydration", `${name}-${version} retrieved`).catch(console.error);
return Response.json(result);
} catch (err) {
publishMessage(
"GET",
"get/form_hydration",
`Failed to retrieve ${name}-${version}`
).catch(console.error);
return Response.json(
{ error: err instanceof Error ? err.message : String(err) },
{ status: 400 }
);
}
}
Loading
Loading