UNPKG

koa-parser

Version:
78 lines (77 loc) 2.98 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; const parser_1 = __importDefault(require("./parser")); module.exports = ({ encoding = 'utf-8', // 编码 error, // 解析错误回调 json = [], // 支持json解析 multipart = [], // 支持form-data解析 text = [], // 支持text解析 urlencoded = [] // 支持urlencoded解析 } = {}) => { if (typeof json === 'string') json = [json]; if (typeof multipart === 'string') multipart = [multipart]; if (typeof text === 'string') text = [text]; if (typeof urlencoded === 'string') urlencoded = [urlencoded]; // 支持的json类型 const jsonTypes = [ 'application/json', 'application/json-patch+json', 'application/vnd.api+json', 'application/csp-report', ...json ]; // 支持的multipart类型 const multipartTypes = ['multipart/form-data', ...multipart]; // 支持的text类型 const textTypes = ['text/plain', ...text]; // 支持的urlencode类型 const urlencodedTypes = ['application/x-www-form-urlencoded', ...urlencoded]; return (ctx, next) => __awaiter(this, void 0, void 0, function* () { // 已经被解析过的情况 if (ctx.request.body !== undefined) { return next(); } try { // 存放请求体 if (ctx.is(jsonTypes)) { // 解析json ctx.request.body = yield parser_1.default.json(ctx, { encoding }); } else if (ctx.is(multipartTypes)) { // 解析multipart ctx.request.body = yield parser_1.default.multipart(ctx, { encoding }); } else if (ctx.is(textTypes)) { // 解析text ctx.request.body = yield parser_1.default.text(ctx, { encoding }); } else if (ctx.is(urlencodedTypes)) { // 解析urlencoded ctx.request.body = yield parser_1.default.urlencoded(ctx, { encoding }); } } catch (err) { if (typeof error === 'function') { error(err, ctx); } else { throw err; } } return next(); }); };