Skip to content

Commit

Permalink
fix: Fix local development post request proxy to https
Browse files Browse the repository at this point in the history
  • Loading branch information
anncwb committed Oct 28, 2020
1 parent a57fd2f commit 7965604
Show file tree
Hide file tree
Showing 4 changed files with 166 additions and 21 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "vite-plugin-mock",
"version": "1.0.4",
"version": "1.0.6",
"description": "A mock plugin for vite",
"main": "dist/index.js",
"files": [
Expand Down
42 changes: 25 additions & 17 deletions src/createMockServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import { isArray, isFunction, sleep, isRegExp } from './utils';
import { loadConfigFromBundledFile } from './loadConfigFromBundledFile';
import { rollup } from 'rollup';
import esbuildPlugin from 'rollup-plugin-esbuild';
// @ts-ignore
import bodyParser from './koaBodyparse';
const pathResolve = require('@rollup/plugin-node-resolve');

let mockData: MockMethod[] = [];
Expand Down Expand Up @@ -37,24 +39,30 @@ export function getMockData() {
}

// request match
export async function requestMiddle(ctx: ParameterizedContext<DefaultState, Context>, next: any) {
const path = ctx.path;
const req = mockData.find((item) => item.url === path);
if (req) {
const { response, timeout } = req;
if (timeout) {
await sleep(timeout);
}
const { body, query } = ctx.request;
const mockRes = isFunction(response) ? response({ body, query }) : response;
console.log(`${chalk.green('[vite:mock-server]:request invoke: ' + ` ${chalk.cyan(path)} `)}`);
ctx.type = 'json';
ctx.status = 200;
export function requestMiddle(app: any) {
return async (ctx: ParameterizedContext<DefaultState, Context>, next: any) => {
const path = ctx.path;
const req = mockData.find((item) => item.url === path);
if (req) {
const { response, timeout } = req;
if (timeout) {
await sleep(timeout);
}
const { query } = ctx.request;
const bodyParserFn = bodyParser(app);
const body = await bodyParserFn(ctx);
const mockRes = isFunction(response) ? response({ body, query }) : response;
console.log(
`${chalk.green('[vite:mock-server]:request invoke: ' + ` ${chalk.cyan(path)} `)}`
);
ctx.type = 'json';
ctx.status = 200;

ctx.body = Mock.mock(mockRes);
return;
}
await next();
ctx.body = Mock.mock(mockRes);
return;
}
await next();
};
}

// create watch mock
Expand Down
137 changes: 137 additions & 0 deletions src/koaBodyparse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
/** !
* koa-body-parser - index.js
* Copyright(c) 2014
* MIT Licensed
*
* Authors:
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
* fengmk2 <m@fengmk2.com> (http://fengmk2.com)
*/

'use strict';

/**
* Module dependencies.
*/
// @ts-ignore
import parse from 'co-body';
// @ts-ignore
import copy from 'copy-to';

/**
* @param [Object] opts
* - {String} jsonLimit default '1mb'
* - {String} formLimit default '56kb'
* - {string} encoding default 'utf-8'
* - {Object} extendTypes
*/

module.exports = function (opts: any) {
opts = opts || {};
const { detectJSON } = opts;
const { onerror } = opts;

const enableTypes = opts.enableTypes || ['json', 'form'];
const enableForm = checkEnable(enableTypes, 'form');
const enableJson = checkEnable(enableTypes, 'json');
const enableText = checkEnable(enableTypes, 'text');
const enableXml = checkEnable(enableTypes, 'xml');

opts.detectJSON = undefined;
opts.onerror = undefined; // eslint-disable-line unicorn/prefer-add-event-listener

// force co-body return raw body
opts.returnRawBody = true;

// default json types
const jsonTypes = [
'application/json',
'application/json-patch+json',
'application/vnd.api+json',
'application/csp-report',
];

// default form types
const formTypes = ['application/x-www-form-urlencoded'];

// default text types
const textTypes = ['text/plain'];

// default xml types
const xmlTypes = ['text/xml', 'application/xml'];

const jsonOpts = formatOptions(opts, 'json');
const formOpts = formatOptions(opts, 'form');
const textOpts = formatOptions(opts, 'text');
const xmlOpts = formatOptions(opts, 'xml');

const extendTypes = opts.extendTypes || {};

extendType(jsonTypes, extendTypes.json);
extendType(formTypes, extendTypes.form);
extendType(textTypes, extendTypes.text);
extendType(xmlTypes, extendTypes.xml);

// eslint-disable-next-line func-names
return async function bodyParser(ctx: any) {
if (ctx.request.body !== undefined || ctx.disableBodyParser) return; // eslint-disable-line no-return-await
try {
const res = await parseBody(ctx);
return 'parsed' in res ? res.parsed : {};

// ctx.request.body = 'parsed' in res ? res.parsed : {};
// if (ctx.request.rawBody === undefined) ctx.request.rawBody = res.raw;
} catch (err) {
if (onerror) {
onerror(err, ctx);
} else {
throw err;
}
}

// await next();
};

async function parseBody(ctx: any) {
if (enableJson && ((detectJSON && detectJSON(ctx)) || ctx.request.is(jsonTypes))) {
return await parse.json(ctx, jsonOpts); // eslint-disable-line no-return-await
}

if (enableForm && ctx.request.is(formTypes)) {
return await parse.form(ctx, formOpts); // eslint-disable-line no-return-await
}

if (enableText && ctx.request.is(textTypes)) {
return (await parse.text(ctx, textOpts)) || '';
}

if (enableXml && ctx.request.is(xmlTypes)) {
return (await parse.text(ctx, xmlOpts)) || '';
}

return {};
}
};

function formatOptions(opts: any, type: any) {
const res: any = {};
copy(opts).to(res);
res.limit = opts[type + 'Limit'];
return res;
}

function extendType(original: any, extend: any) {
if (extend) {
if (!Array.isArray(extend)) {
extend = [extend];
}

extend.forEach(function (extend: any) {
original.push(extend);
});
}
}

function checkEnable(types: any, type: any) {
return types.includes(type);
}
6 changes: 3 additions & 3 deletions src/mockServerPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import { ServerPlugin } from 'vite';

import { createMockServer, requestMiddle } from './createMockServer';
import { CreateMock } from './types';
import bodyParser from 'koa-bodyparser';
// import bodyParser from 'koa-bodyparser';

export const createMockServerPlugin = (opt: CreateMock): ServerPlugin => {
return ({ app }) => {
app.use(bodyParser());
// app.use(bodyParser());
createMockServer(opt);
app.use(requestMiddle);
app.use(requestMiddle(app));
};
};

0 comments on commit 7965604

Please sign in to comment.