Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#167 into [email protected] 🐘 call server response interceptors for database requests, add database api interceptors, add baseUrl field for database #170

Closed
wants to merge 5 commits into from
Closed
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
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import { z } from 'zod';

import { baseUrlSchema } from '../baseUrlSchema/baseUrlSchema';
import { interceptorsSchema } from '../interceptorsSchema/interceptorsSchema';
import { plainObjectSchema, stringForwardSlashSchema, stringJsonFilenameSchema } from '../utils';

export const databaseConfigSchema = z.strictObject({
baseUrl: baseUrlSchema.optional(),
data: z.union([plainObjectSchema(z.record(z.unknown())), stringJsonFilenameSchema]),
routes: z
.union([
plainObjectSchema(z.record(stringForwardSlashSchema, stringForwardSlashSchema)),
stringJsonFilenameSchema
])
.optional()
.optional(),
interceptors: plainObjectSchema(interceptorsSchema).optional()
});
166 changes: 85 additions & 81 deletions src/core/database/createDatabaseRoutes/createDatabaseRoutes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,108 +5,112 @@ import path from 'path';
import request from 'supertest';

import { createDatabaseRoutes } from '@/core/database';
import { urlJoin } from '@/utils/helpers';
import { createTmpDir } from '@/utils/helpers/tests';
import type { DatabaseConfig, MockServerConfig } from '@/utils/types';

import { findIndexById } from './helpers';

describe('createDatabaseRoutes', () => {
const createServer = (
mockServerConfig: Pick<MockServerConfig, 'baseUrl'> & { database: DatabaseConfig }
) => {
const server = express();
const routerBase = express.Router();
const routesWithDatabaseRoutes = createDatabaseRoutes(routerBase, mockServerConfig.database);

server.use(mockServerConfig.baseUrl ?? '/', routesWithDatabaseRoutes);
return server;
};

describe('createDatabaseRoutes: routes and data successfully works when passing them by object', () => {
const data = { profile: { name: 'John' }, users: [{ id: 1 }, { id: 2 }] };
const routes = { '/api/profile': '/profile' } as const;
const server = createServer({ database: { data, routes } });

test('Should overwrite routes according to routes object (but default url should work too)', async () => {
const overwrittenUrlResponse = await request(server).get('/api/profile');
expect(overwrittenUrlResponse.body).toStrictEqual(data.profile);

const defaultUrlResponse = await request(server).get('/profile');
expect(defaultUrlResponse.body).toStrictEqual(data.profile);
});

test('Should successfully handle requests to shallow and nested database parts', async () => {
const shallowDatabaseResponse = await request(server).get('/profile');
expect(shallowDatabaseResponse.body).toStrictEqual(data.profile);

const nestedDatabaseCollectionResponse = await request(server).get('/users');
expect(nestedDatabaseCollectionResponse.body).toStrictEqual(data.users);

const nestedDatabaseItemResponse = await request(server).get('/users/1');
expect(nestedDatabaseItemResponse.body).toStrictEqual(
data.users[findIndexById(data.users, 1)]
);
});
const createServer = (
mockServerConfig: Pick<MockServerConfig, 'interceptors' | 'baseUrl'> & {
database: DatabaseConfig;
}
) => {
const { baseUrl, database, interceptors } = mockServerConfig;
const server = express();
const routerBase = express.Router();
const routesWithDatabaseRoutes = createDatabaseRoutes({
router: routerBase,
databaseConfig: database,
serverResponseInterceptor: interceptors?.response
});

describe('createDatabaseRoutes: routes and data successfully works when passing them by file', () => {
const data = { profile: { name: 'John' }, users: [{ id: 1 }, { id: 2 }] };
const routes = { '/api/profile': '/profile' } as const;
const databaseBaseUrl = urlJoin(baseUrl ?? '/', database?.baseUrl ?? '/');

let tmpDirPath: string;
let server: Express;
server.use(databaseBaseUrl, routesWithDatabaseRoutes);
return server;
};

beforeAll(() => {
tmpDirPath = createTmpDir();
describe('createDatabaseRoutes: routes and data successfully works when passing them by object', () => {
const data = { profile: { name: 'John' }, users: [{ id: 1 }, { id: 2 }] };
const routes = { '/api/profile': '/profile' } as const;
const server = createServer({ database: { data, routes } });

const pathToData = path.join(tmpDirPath, './data.json') as `${string}.json`;
fs.writeFileSync(pathToData, JSON.stringify(data));
test('Should overwrite routes according to routes object (but default url should work too)', async () => {
const overwrittenUrlResponse = await request(server).get('/api/profile');
expect(overwrittenUrlResponse.body).toStrictEqual(data.profile);

const pathToRoutes = path.join(tmpDirPath, './routes.json') as `${string}.json`;
fs.writeFileSync(pathToRoutes, JSON.stringify(routes));
const defaultUrlResponse = await request(server).get('/profile');
expect(defaultUrlResponse.body).toStrictEqual(data.profile);
});

test('Should successfully handle requests to shallow and nested database parts', async () => {
const shallowDatabaseResponse = await request(server).get('/profile');
expect(shallowDatabaseResponse.body).toStrictEqual(data.profile);

const nestedDatabaseCollectionResponse = await request(server).get('/users');
expect(nestedDatabaseCollectionResponse.body).toStrictEqual(data.users);

const nestedDatabaseItemResponse = await request(server).get('/users/1');
expect(nestedDatabaseItemResponse.body).toStrictEqual(data.users[findIndexById(data.users, 1)]);
});
});

describe('createDatabaseRoutes: routes and data successfully works when passing them by file', () => {
const data = { profile: { name: 'John' }, users: [{ id: 1 }, { id: 2 }] };
const routes = { '/api/profile': '/profile' } as const;

let tmpDirPath: string;
let server: Express;

server = createServer({ database: { data: pathToData, routes: pathToRoutes } });
});
beforeAll(() => {
tmpDirPath = createTmpDir();

afterAll(() => {
fs.rmSync(tmpDirPath, { recursive: true, force: true });
});
const pathToData = path.join(tmpDirPath, './data.json') as `${string}.json`;
fs.writeFileSync(pathToData, JSON.stringify(data));

test('Should overwrite routes according to routes object (but default url should work too)', async () => {
const overwrittenUrlResponse = await request(server).get('/api/profile');
expect(overwrittenUrlResponse.body).toStrictEqual(data.profile);
const pathToRoutes = path.join(tmpDirPath, './routes.json') as `${string}.json`;
fs.writeFileSync(pathToRoutes, JSON.stringify(routes));

const defaultUrlResponse = await request(server).get('/profile');
expect(defaultUrlResponse.body).toStrictEqual(data.profile);
});
server = createServer({ database: { data: pathToData, routes: pathToRoutes } });
});

afterAll(() => {
fs.rmSync(tmpDirPath, { recursive: true, force: true });
});

test('Should overwrite routes according to routes object (but default url should work too)', async () => {
const overwrittenUrlResponse = await request(server).get('/api/profile');
expect(overwrittenUrlResponse.body).toStrictEqual(data.profile);

test('Should successfully handle requests to shallow and nested database parts', async () => {
const shallowDatabaseResponse = await request(server).get('/profile');
expect(shallowDatabaseResponse.body).toStrictEqual(data.profile);
const defaultUrlResponse = await request(server).get('/profile');
expect(defaultUrlResponse.body).toStrictEqual(data.profile);
});

test('Should successfully handle requests to shallow and nested database parts', async () => {
const shallowDatabaseResponse = await request(server).get('/profile');
expect(shallowDatabaseResponse.body).toStrictEqual(data.profile);

const nestedDatabaseCollectionResponse = await request(server).get('/users');
expect(nestedDatabaseCollectionResponse.body).toStrictEqual(data.users);
const nestedDatabaseCollectionResponse = await request(server).get('/users');
expect(nestedDatabaseCollectionResponse.body).toStrictEqual(data.users);

const nestedDatabaseItemResponse = await request(server).get('/users/1');
expect(nestedDatabaseItemResponse.body).toStrictEqual(
data.users[findIndexById(data.users, 1)]
);
});
const nestedDatabaseItemResponse = await request(server).get('/users/1');
expect(nestedDatabaseItemResponse.body).toStrictEqual(data.users[findIndexById(data.users, 1)]);
});
});

describe('createDatabaseRoutes: routes /__routes and /__db', () => {
const data = { profile: { name: 'John' }, users: [{ id: 1 }, { id: 2 }] };
const routes = { '/api/profile': '/profile' } as const;
const server = createServer({ database: { data, routes } });
describe('createDatabaseRoutes: routes /__routes and /__db', () => {
const data = { profile: { name: 'John' }, users: [{ id: 1 }, { id: 2 }] };
const routes = { '/api/profile': '/profile' } as const;
const server = createServer({ database: { data, routes } });

test('Should create /__db route that return data from databaseConfig', async () => {
const response = await request(server).get('/__db');
expect(response.body).toStrictEqual(data);
});
test('Should create /__db route that return data from databaseConfig', async () => {
const response = await request(server).get('/__db');
expect(response.body).toStrictEqual(data);
});

test('Should create /__routes route that return routes from databaseConfig', async () => {
const response = await request(server).get('/__routes');
expect(response.body).toStrictEqual(routes);
});
test('Should create /__routes route that return routes from databaseConfig', async () => {
const response = await request(server).get('/__routes');
expect(response.body).toStrictEqual(routes);
});
});
36 changes: 32 additions & 4 deletions src/core/database/createDatabaseRoutes/createDatabaseRoutes.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { IRouter } from 'express';

import type { DatabaseConfig, NestedDatabase, ShallowDatabase } from '@/utils/types';
import type { DatabaseConfig, Interceptors, NestedDatabase, ShallowDatabase } from '@/utils/types';

import {
createNestedDatabaseRoutes,
Expand All @@ -13,7 +13,19 @@ import { FileStorage, MemoryStorage } from './storages';
const isVariableJsonFile = (variable: unknown): variable is `${string}.json` =>
typeof variable === 'string' && variable.endsWith('.json');

export const createDatabaseRoutes = (router: IRouter, { data, routes }: DatabaseConfig) => {
interface CreateDatabaseRoutesParams {
router: IRouter;
databaseConfig: DatabaseConfig;
serverResponseInterceptor?: Interceptors['response'];
}

export const createDatabaseRoutes = ({
router,
databaseConfig,
serverResponseInterceptor
}: CreateDatabaseRoutesParams) => {
const { data, routes } = databaseConfig;

if (routes) {
const storage = isVariableJsonFile(routes)
? new FileStorage(routes)
Expand All @@ -27,8 +39,24 @@ export const createDatabaseRoutes = (router: IRouter, { data, routes }: Database

const storage = isVariableJsonFile(data) ? new FileStorage(data) : new MemoryStorage(data);
const { shallowDatabase, nestedDatabase } = splitDatabaseByNesting(storage.read());
createShallowDatabaseRoutes(router, shallowDatabase, storage as MemoryStorage<ShallowDatabase>);
createNestedDatabaseRoutes(router, nestedDatabase, storage as MemoryStorage<NestedDatabase>);
createShallowDatabaseRoutes({
router,
database: shallowDatabase,
storage: storage as MemoryStorage<ShallowDatabase>,
responseInterceptors: {
apiInterceptor: databaseConfig.interceptors?.response,
serverInterceptor: serverResponseInterceptor
}
});
createNestedDatabaseRoutes({
router,
database: nestedDatabase,
storage: storage as MemoryStorage<NestedDatabase>,
responseInterceptors: {
apiInterceptor: databaseConfig.interceptors?.response,
serverInterceptor: serverResponseInterceptor
}
});

router.route('/__db').get((_request, response) => {
response.json(storage.read());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import type { Express } from 'express';
import express from 'express';
import request from 'supertest';

import type { NestedDatabase } from '@/utils/types';
import type { Interceptors, NestedDatabase } from '@/utils/types';

import { MemoryStorage } from '../../storages';

import { createNestedDatabaseRoutes } from './createNestedDatabaseRoutes';

describe('CreateNestedDatabaseRoutes', () => {
describe('createNestedDatabaseRoutes', () => {
const createNestedDatabase = () => ({
users: [
{
Expand All @@ -28,16 +28,23 @@ describe('CreateNestedDatabaseRoutes', () => {
]
});

const createServer = (nestedDatabase: NestedDatabase) => {
const createServer = (
nestedDatabase: NestedDatabase,
responseInterceptors?: {
apiInterceptor?: Interceptors['response'];
serverInterceptor?: Interceptors['response'];
}
) => {
const server = express();
const routerBase = express.Router();
const storage = new MemoryStorage(nestedDatabase);

const routerWithNestedDatabaseRoutes = createNestedDatabaseRoutes(
routerBase,
nestedDatabase,
storage
);
const routerWithNestedDatabaseRoutes = createNestedDatabaseRoutes({
router: routerBase,
database: nestedDatabase,
storage,
responseInterceptors
});

server.use(express.json());
server.use(express.text());
Expand Down Expand Up @@ -675,4 +682,19 @@ describe('CreateNestedDatabaseRoutes', () => {
]);
});
});

describe('createNestedDatabaseRoutes: interceptors', () => {
test('Should call response interceptors', async () => {
const apiInterceptor = vi.fn();
const serverInterceptor = vi.fn();

const nestedDatabase = createNestedDatabase();
const server = createServer(nestedDatabase, { apiInterceptor, serverInterceptor });

await request(server).get('/users');

expect(apiInterceptor.mock.calls.length).toBe(1);
expect(serverInterceptor.mock.calls.length).toBe(1);
});
});
});
Loading