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
1 change: 1 addition & 0 deletions .github/ISSUE_TEMPLATE/bug-report.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ body:
- Liquidjs Operation
- Extension Meter Component
- Migration Bundle
- Mock API Bundle
- PDF Viewer Interface
- Plausible Analytics Bundle
- Related Items Bundle
Expand Down
1 change: 1 addition & 0 deletions .github/ISSUE_TEMPLATE/enhancement.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ body:
- Liquidjs Operation
- Extension Meter Component
- Migration Bundle
- Mock API Bundle
- PDF Viewer Interface
- Plausible Analytics Bundle
- Related Items Bundle
Expand Down
69 changes: 69 additions & 0 deletions packages/mock-api-bundle/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Directus Mock API

Create mock API endpoints from Studio, so you can build frontend work against APIs that don't exist yet.

## Install

Requires Directus 12. Refer to the official guide for installing the extension from the Marketplace or manually. The bundle includes an API endpoint and hook that aren't sandboxed, so installing it from the Marketplace requires `MARKETPLACE_TRUST=all`.

When Directus starts, the extension creates its own hidden collections (`mock_api_*`).

Enable the **Mock API** module under **Settings → Project Settings → Modules**. Only admins can see it.

## Use

1. Open **Mock API** and create a collection, or click **Add example** to start from a sample tasks API.
2. Give the collection a prefix, such as `tasks-api`. Every endpoint in it is served under `/mock/<prefix>`.
3. Add endpoints. Each one needs a method, a path and one or more responses (status and JSON body). Pick the **active response** to switch what the endpoint returns, for example from a `200` to a `500`.
4. Call it:

```sh
curl -H "Authorization: Bearer <token>" https://your-project/mock/tasks-api/tasks/5
```

Use the **Test request** panel on an endpoint to try it without leaving Studio. **Log** shows the last 50 requests and which endpoint answered each one. The log lives in memory, so it clears on restart, and with several API instances each one keeps its own.

### Paths

- `:name` captures a path segment, e.g. `/tasks/:id`.
- A trailing `*` matches the rest of the path, which must have at least one more segment.
- **Query** limits an endpoint to requests that include those values, e.g. `shared=true`.
- When several endpoints match, the most specific one answers.

### Response tokens

Response bodies can include these tokens:

| Token | Value |
| ---------------- | ------------------------------ |
| `{{params.id}}` | A path param |
| `{{query.name}}` | A query string value |
| `{{body.title}}` | A field from the request body |
| `{{now}}` | The current time (ISO 8601) |
| `{{uuid}}` | A new UUID |

Tokens can go inside quotes or where a number goes, e.g. `{"id": {{params.id}}}`. Inside quotes, values are escaped so the JSON stays valid. Where a number goes, numbers, `true`, `false` and objects are written as JSON, other text is quoted, and a missing value becomes `null`. An empty body returns `204`.

**Delay** waits the given number of milliseconds before responding (30 seconds at most), which helps when testing loading states.

### Import and export

**Transfer** exports collections as a JSON file and imports them into another project. When an imported prefix already exists, choose how to handle it:

- **Merge**: add new endpoints and update matching ones, keeping the rest.
- **Replace**: delete the existing collection and import the file's version.
- **Copy**: import it alongside, with a new prefix such as `tasks-api-2`.

Each import shows a preview of the changes before you apply it.

## Settings

**Require a signed-in user** (Mock API → Settings) is on by default. With it on, mock routes need a valid access token, like any other Directus route. Turn it off only on projects where anonymous access is acceptable.

## Development

```sh
pnpm dev # rebuild on change
pnpm test # run tests
pnpm validate # type check
```
71 changes: 71 additions & 0 deletions packages/mock-api-bundle/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
{
"name": "@directus-labs/mock-api-bundle",
"type": "module",
"version": "1.0.0",
"description": "Create mock API endpoints from Studio for testing frontend work against APIs that don't exist yet.",
"author": "Directus Labs",
"contributors": [
{
"name": "Rob Luton"
}
],
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/directus-labs/extensions.git",
"directory": "packages/mock-api-bundle"
},
"keywords": [
"directus",
"directus-extension",
"directus-extension-bundle"
],
"icon": "api",
"files": [
"dist"
],
"directus:extension": {
"type": "bundle",
"path": {
"app": "dist/app.js",
"api": "dist/api.js"
},
"entries": [
{
"type": "module",
"name": "mock-api",
"source": "src/app/index.ts"
},
{
"type": "endpoint",
"name": "mock-api-router",
"source": "src/api/endpoint.ts"
},
{
"type": "hook",
"name": "mock-api-setup",
"source": "src/api/hook.ts"
}
],
"host": ">=12.0.0 <13"
},
"scripts": {
"build": "directus-extension build",
"dev": "directus-extension build -w --no-minify",
"link": "directus-extension link",
"test": "vitest run",
"validate": "vue-tsc --noEmit"
},
"devDependencies": {
"@directus/errors": "^3.0.0",
"@directus/extensions-sdk": "18.1.0",
"@directus/types": "^18.1.0",
"@types/express": "^4.17.21",
"knex": "^3.1.0",
"typescript": "^5.9.3",
"vitest": "^3.2.4",
"vue": "^3.5.13",
"vue-router": "^4.5.1",
"vue-tsc": "^3.3.14"
}
}
14 changes: 14 additions & 0 deletions packages/mock-api-bundle/src/api/endpoint.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { describe, expect, it } from 'vitest';
import { redactUrl } from './endpoint';

describe('redactUrl', () => {
it('should replace token-like query values and keep the rest', () => {
expect(redactUrl('/mock/bookmarks/pages?access_token=abc123&fields=*&api_key=xyz')).toBe(
'/mock/bookmarks/pages?access_token=redacted&fields=*&api_key=redacted',
);
});

it('should leave a path without a query untouched', () => {
expect(redactUrl('/mock/bookmarks/pages')).toBe('/mock/bookmarks/pages');
});
});
194 changes: 194 additions & 0 deletions packages/mock-api-bundle/src/api/endpoint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
import type { Accountability, EndpointConfig } from '@directus/types';
import type { Request, Response } from 'express';
import { notFoundBody, resolveRequest } from '../shared/engine';
import { errorBody } from '../shared/errors';
import { BASE_PATH } from '../shared/tables';
import { isImportStrategy, validateExport } from '../shared/transfer';
import { ensureSchema } from './schema';
import { applyImport, buildExport, loadMocks, previewImport, requiresAuth } from './store';

interface LogEntry {
time: string;
method: string;
path: string;
status: number;
answered_by: string | null;
}

const LOG_LIMIT = 50;
const MAX_DELAY = 30_000;
const log: LogEntry[] = [];

function accountabilityOf(req: Request): Accountability | null {
return (req as Request & { accountability?: Accountability }).accountability ?? null;
}

function isAdmin(req: Request) {
return accountabilityOf(req)?.admin === true;
}

function sendBody(res: Response, status: number, body: string) {
if (!body.trim() || status === 204 || status === 304) {
res.status(status).end();
return;
}

try {
JSON.parse(body);
res.status(status).type('application/json').send(body);
}
catch {
res.status(status).type('text/plain').send(body);
}
}

const SENSITIVE_QUERY = /token|key|secret|password|auth|session|code/i;

export function redactUrl(url: string): string {
const [path = '', query] = url.split('?');
if (!query) return path;

const params = new URLSearchParams(query);

for (const key of params.keys()) {
if (SENSITIVE_QUERY.test(key)) params.set(key, 'redacted');
}

return `${path}?${params.toString()}`;
}

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

const endpoint: EndpointConfig = {
id: BASE_PATH,
handler: (router, context) => {
const adminOnly = (req: Request, res: Response) => {
if (isAdmin(req)) return true;
res.status(403).json(errorBody('Only admins can manage mocks.', 'FORBIDDEN'));
return false;
};

router.get('/_meta/log', (req, res) => {
if (!adminOnly(req, res)) return;
res.json({ data: log });
});

router.delete('/_meta/log', (req, res) => {
if (!adminOnly(req, res)) return;
log.length = 0;
res.status(204).end();
});

router.get('/_meta/export', async (req, res, next) => {
if (!adminOnly(req, res)) return;

try {
await ensureSchema(context);
const ids = String(req.query['collections'] ?? '')
.split(',')
.map(Number)
.filter((id) => Number.isInteger(id) && id > 0);

const file = await buildExport(context.database, ids.length > 0 ? ids : undefined);
const name = file.collections.map((c) => c.prefix).join('-') || 'empty';
res.setHeader('Content-Disposition', `attachment; filename="mock-api-${name}.json"`);
res.json(file);
}
catch (error) {
next(error);
}
});

router.post('/_meta/import', async (req, res, next) => {
if (!adminOnly(req, res)) return;

try {
await ensureSchema(context);
const strategy = req.body?.strategy ?? 'merge';

if (!isImportStrategy(strategy)) {
res
.status(400)
.json(errorBody(`Unknown strategy "${strategy}". Use merge, replace or copy.`, 'INVALID_PAYLOAD'));

return;
}

const result = validateExport(req.body?.file);

if ('error' in result) {
res.status(400).json(errorBody(result.error, 'INVALID_PAYLOAD'));
return;
}

const plan = req.body?.dry_run
? await previewImport(context.database, result.file, strategy)
: await applyImport(context, accountabilityOf(req), result.file, strategy);

res.json({ data: { ...plan, applied: !req.body?.dry_run } });
}
catch (error) {
next(error);
}
});

router.all('*', async (req, res) => {
const path = req.path;
const query = new URLSearchParams(req.originalUrl.split('?')[1] ?? '');
const entry: LogEntry = {
time: new Date().toISOString(),
method: req.method,
path: redactUrl(req.originalUrl),
status: 404,
answered_by: null,
};

try {
await ensureSchema(context);

if ((await requiresAuth(context.database)) && !accountabilityOf(req)?.user) {
entry.status = 403;

res
.status(403)
.json(
errorBody(
'Sign in to use mock endpoints, or turn off "Require a signed-in user" in Mock API settings.',
'FORBIDDEN',
),
);

return;
}

const resolved = resolveRequest(await loadMocks(context.database), {
method: req.method,
path,
query,
body: req.body,
});

if (!resolved) {
sendBody(res, 404, notFoundBody(req.method, path));
return;
}

entry.status = resolved.status;
entry.answered_by = `${resolved.collection.name} / ${resolved.endpoint.name}`;
if (resolved.delay) await sleep(Math.min(resolved.delay, MAX_DELAY));
sendBody(res, resolved.status, resolved.body);
}
catch (error) {
context.logger.error(error, '[mock-api] Request failed');
entry.status = 500;
res.status(500).json(errorBody('The mock router failed. Check the API logs.', 'INTERNAL_SERVER_ERROR'));
}
finally {
log.unshift(entry);
log.length = Math.min(log.length, LOG_LIMIT);
}
});
},
};

export default endpoint;
26 changes: 26 additions & 0 deletions packages/mock-api-bundle/src/api/hook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import type { HookConfig } from '@directus/types';
import { InvalidPayloadError } from '@directus/errors';
import { bodyError } from '../shared/engine';
import { RESPONSES } from '../shared/tables';
import { ensureSchema } from './schema';

function validateBody(payload: Record<string, any>) {
if (!('body' in payload)) return payload;

const error = bodyError(payload['body']);
if (!error) return payload;

const name = payload['name'] ? `Response "${payload['name']}"` : 'The response body';
throw new InvalidPayloadError({ reason: `${name} isn't valid JSON: ${error}` });
}

const hook: HookConfig = ({ filter, init }, context) => {
init('app.after', () => {
ensureSchema(context).catch(() => {});
});

filter(`${RESPONSES}.items.create`, (payload) => validateBody(payload as Record<string, any>));
filter(`${RESPONSES}.items.update`, (payload) => validateBody(payload as Record<string, any>));
};

export default hook;
Loading
Loading