import qs from 'qs'; import supertest from 'supertest'; import Application, { ApplicationOptions } from '@nocobase/server'; import { ActionParams } from '@nocobase/resourcer'; import { getConfig } from './mockDatabase'; interface Resource { get: (params?: ActionParams) => Promise; list: (params?: ActionParams) => Promise; create: (params?: ActionParams) => Promise; update: (params?: ActionParams) => Promise; destroy: (params?: ActionParams) => Promise; [name: string]: (params?: ActionParams) => Promise; } export class MockServer extends Application { agent() { return supertest.agent(this.callback()); } resource(name: string) { const agent = this.agent(); const keys = name.split('.'); const prefix = this.resourcer.options.prefix; const proxy = new Proxy({}, { get(target, method: string, receiver) { return (params: ActionParams = {}) => { const { associatedKey, resourceKey, values = {}, file, ...restParams } = params; let url = prefix; if (keys.length > 1) { url = `/${keys[0]}/${associatedKey}/${keys[1]}}` } else { url = `/${name}`; } url += `:${method as string}`; if (resourceKey) { url += `/${resourceKey}`; } console.log('request url: ' + url); switch (method) { case 'upload': return agent .post(`${url}?${qs.stringify(restParams)}`) .attach('file', file) .field(values); case 'list': case 'get': return agent.get(`${url}?${qs.stringify(restParams)}`); default: return agent .post(`${url}?${qs.stringify(restParams)}`) .send(values); } }; }, }); return proxy as Resource; } } export function mockServer(options?: ApplicationOptions) { return new MockServer({ ...options, database: getConfig(options?.database), }); } export default mockServer;