|
- import {describe, afterAll, afterEach, beforeAll, beforeEach, it} from 'vitest';
- import {mkdtemp, rm} from 'fs/promises';
- import {join} from 'path';
- import {tmpdir} from 'os';
- import {application, resource, Resource, validation as v} from '../../src/common';
- import {BackendBuilder, dataSources} from '../../src/backend';
- import {autoIncrement} from '../fixtures';
- import {RequestContext} from '../../src/backend/common';
-
- const PORT = 3001;
- const HOST = '127.0.0.1';
- const BASE_PATH = '/api';
- const ACCEPT = 'application/json';
- const ACCEPT_LANGUAGE = 'en';
- const CONTENT_TYPE_CHARSET = 'utf-8';
- const CONTENT_TYPE = ACCEPT;
-
- describe('decorators', () => {
- let baseDir: string;
- beforeAll(async () => {
- try {
- baseDir = await mkdtemp(join(tmpdir(), 'yasumi-'));
- } catch {
- // noop
- }
- });
- afterAll(async () => {
- try {
- await rm(baseDir, {
- recursive: true,
- });
- } catch {
- // noop
- }
- });
-
- let Piano: Resource;
- beforeEach(() => {
- Piano = resource(v.object(
- {
- brand: v.string()
- },
- v.never()
- ))
- .name('Piano' as const)
- .route('pianos' as const)
- .id('id' as const, {
- generationStrategy: autoIncrement,
- serialize: (id) => id?.toString() ?? '0',
- deserialize: (id) => Number.isFinite(Number(id)) ? Number(id) : 0,
- schema: v.number(),
- });
- });
-
- let server: ReturnType<BackendBuilder['createHttpServer']>;
- beforeEach(() => {
- const app = application({
- name: 'piano-service',
- })
- .resource(Piano);
-
- const backend = app
- .createBackend({
- dataSource: new dataSources.jsonlFile.DataSource(baseDir),
- })
- .throwsErrorOnDeletingNotFound();
-
- server = backend.createHttpServer({
- basePath: BASE_PATH
- });
-
- return new Promise((resolve, reject) => {
- server.on('error', (err) => {
- reject(err);
- });
-
- server.on('listening', () => {
- resolve();
- });
-
- server.listen({
- port: PORT
- });
- });
- });
-
- afterEach(() => new Promise((resolve, reject) => {
- server.close((err) => {
- if (err) {
- reject(err);
- }
-
- resolve();
- });
- }));
-
- it('decorates requests', () => {
- server.requestDecorator((req) => {
- const reqMut = req as unknown as Record<string, unknown>;
- reqMut['foo'] = 'bar';
- return reqMut as unknown as RequestContext;
- });
-
- // TODO how to make assertions here
- });
- });
|