Skip to content

Commit

Permalink
feat(server): add this for response, rawResponse function (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
wention committed Aug 22, 2021
1 parent db2c7b4 commit 2f4d6d2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
17 changes: 12 additions & 5 deletions src/createMockServer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import type { ViteMockOptions, MockMethod, NodeModuleWithCompile, Recordable } from './types';
import type {
ViteMockOptions,
MockMethod,
NodeModuleWithCompile,
Recordable,
RespThisType,
} from './types';

import path from 'path';
import fs from 'fs';
Expand Down Expand Up @@ -81,15 +87,16 @@ export async function requestMiddleware(opt: ViteMockOptions) {
}
}

const self: RespThisType = { req, res, parseJson: parseJson.bind(null, req) };
if (isFunction(rawResponse)) {
await rawResponse(req, res);
await rawResponse.bind(self)(req, res);
} else {
const body = await parseJson(req);
const mockResponse = isFunction(response)
? response({ url: req.url, body, query, headers: req.headers })
: response;
res.setHeader('Content-Type', 'application/json');
res.statusCode = statusCode || 200;
const mockResponse = isFunction(response)
? response.bind(self)({ url: req.url, body, query, headers: req.headers })
: response;
res.end(JSON.stringify(Mock.mock(mockResponse)));
}

Expand Down
13 changes: 11 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ export interface ViteMockOptions {
logger?: boolean;
}

export interface RespThisType {
req: IncomingMessage;
res: ServerResponse;
parseJson: () => any;
}

export type MethodType = 'get' | 'post' | 'put' | 'delete' | 'patch';

export type Recordable<T = any> = Record<string, T>;
Expand All @@ -26,9 +32,12 @@ export declare interface MockMethod {
timeout?: number;
statusCode?: number;
response?:
| ((opt: { url: Recordable; body: Recordable; query: Recordable; headers: Recordable }) => any)
| ((
this: RespThisType,
opt: { url: Recordable; body: Recordable; query: Recordable; headers: Recordable }
) => any)
| any;
rawResponse?: (req: IncomingMessage, res: ServerResponse) => void;
rawResponse?: (this: RespThisType, req: IncomingMessage, res: ServerResponse) => void;
}

export interface NodeModuleWithCompile extends NodeModule {
Expand Down

0 comments on commit 2f4d6d2

Please sign in to comment.