All files / server/plugins/parser index.js

100% Statements 28/28
100% Branches 16/16
100% Functions 9/9
100% Lines 22/22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95        27x                                                                 117x           136x 135x 534x         136x 135x 135x         136x 135x 135x         136x 135x 135x         136x 135x 135x         136x 135x       135x         136x         27x  
// Parser plugin
// Get the raw request and transform it into something usable
// Examples: ctx.body, ctx.files, etc
 
const plugin = {
  name: 'parser',
  options: {
    body: {
      type: [Object, Boolean],
      default: { extended: true },
      extend: true
    },
    json: {
      type: [Object, Boolean],
      default: {}
    },
    text: {
      type: Object,
      default: {}
    },
    data: {
      type: Object,
      default: {}
    },
    cookie: {
      type: Object,
      default: {}
    },
    method: {
      type: [Object, String, Boolean],
      default: [
        'X-HTTP-Method',
        'X-HTTP-Method-Override',
        'X-Method-Override',
        '_method'
      ],
      // Coerce it into an Array if it is not already
      clean: value => typeof value === 'string' ? [value] : value
    }
  },
 
  before: [
    ctx => {
      if (!ctx.options.parser.method) return;
      return ctx.utils.join(ctx.options.parser.method.map(one => {
        return ctx.utils.modern(require('method-override')(one));
      }))(ctx);
    },
 
    ctx => {
      if (!ctx.options.parser.body) return;
      const body = require('body-parser').urlencoded(ctx.options.parser.body);
      return ctx.utils.modern(body)(ctx);
    },
 
    // JSON parser
    ctx => {
      if (!ctx.options.parser.json) return;
      const json = require('body-parser').json(ctx.options.parser.json);
      return ctx.utils.modern(json)(ctx);
    },
 
    // Text parser
    ctx => {
      if (!ctx.options.parser.text) return;
      const text = require('body-parser').text(ctx.options.parser.text);
      return ctx.utils.modern(text)(ctx);
    },
 
    // Data parser
    ctx => {
      if (!ctx.options.parser.data) return;
      const data = require('express-data-parser')(ctx.options.parser.data);
      return ctx.utils.modern(data)(ctx);
    },
 
    // Cookie parser
    ctx => {
      if (!ctx.options.parser.cookie) return;
      const cookie = require('cookie-parser')(
        ctx.options.secret,
        ctx.options.parser.cookie
      );
      return ctx.utils.modern(cookie)(ctx);
    },
 
    // Add a reference from ctx.req.body to the ctx.data and an alias
    ctx => {
      ctx.data = ctx.data || ctx.body;
    },
  ]
};
 
module.exports = plugin;