context.js/koa-convert/is-generator-function for koa source code reading

Keywords: Javascript github socket Attribute

Old fellow hey

Today, let's talk about koa's context.js and some libraries written by tj itself.

context.js

'use strict';
const createError = require('http-errors');
const httpAssert = require('http-assert');
const delegate = require('delegates');
const statuses = require('statuses');

const proto = module.exports = {

    //As mentioned in the previous article, this is not described here.
  inspect() {
    if (this === proto) return this;
    return this.toJSON();
  },

  toJSON() {
    return {
      request: this.request.toJSON(),//Actually call toJSON of request.js (the same below)
      response: this.response.toJSON(),
      app: this.app.toJSON(),
      originalUrl: this.originalUrl,
      req: '<original node req>',
      res: '<original node res>',
      socket: '<original node socket>'
    };
  },

  /**
   * Similar to .throw(), adds assertion.
   *
   *    this.assert(this.user, 401, 'Please login!');
   *
   * See: https://github.com/jshttp/http-assert
   *
   * @param {Mixed} test
   * @param {Number} status
   * @param {String} message
   * @api public
   */

  assert: httpAssert,

  /**
   * Throw an error with `msg` and optional `status`
   * defaulting to 500. Note that these are user-level
   * errors, and the message may be exposed to the client.
   *
   *    this.throw(403)
   *    this.throw('name required', 400)
   *    this.throw(400, 'name required')
   *    this.throw('something exploded')
   *    this.throw(new Error('invalid'), 400);
   *    this.throw(400, new Error('invalid'));
   *
   * See: https://github.com/jshttp/http-errors
   *
   * @param {String|Number|Error} err, msg or status
   * @param {String|Number|Error} [err, msg or status]
   * @param {Object} [props]
   * @api public
   */
    //Throw method. The above is the method used. We often use throw to send out some error status codes in middleware.
    //This allows superior middleware to try catch to respond to this error
    //createError([status], [message], [properties])
    //properties - custom properties to attach to the object
  throw(...args) {
    throw createError(...args);
  },
    //Default error handling
  onerror(err) {
    // don't do anything if there is no error.
    // this allows you to pass `this.onerror`
    // to node-style callbacks.
    if (null == err) return;
    // If the error is not an Error instance. At this point, an error instance is generated for processing below.
    if (!(err instanceof Error)) err = new Error(`non-error thrown: ${err}`);

    let headerSent = false;
    //Of course, it needs to be writable and not sent.
    if (this.headerSent || !this.writable) {
      headerSent = err.headerSent = true;
    }

    //Trigger event
    this.app.emit('error', err, this);

    //I'm sure I can't do anything with it.
    if (headerSent) {
      return;
    }

    const { res } = this;
    //Deconstruct to get a response
    
    //Compatible with
    //Clear all headers for the first time
    if (typeof res.getHeaderNames === 'function') {
      res.getHeaderNames().forEach(name => res.removeHeader(name));
    } else {
      res._headers = {}; // Node < 7.7
    }

    // Then set it to the wrong headers identifier
    this.set(err.headers);

    //Force text/plain
    this.type = 'text';

    // Support ENOENT 
    if ('ENOENT' == err.code) err.status = 404;

    // Default conversion to 500 status code
    if ('number' != typeof err.status || !statuses[err.status]) err.status = 500;

    //response
    const code = statuses[err.status];
    const msg = err.expose ? err.message : code;
    this.status = err.status;
    this.length = Buffer.byteLength(msg);
    this.res.end(msg);
    //It's the same as the original.
    //Give us a hint. We need to close a connection. Then ctx.res.end(msg);
  }
};

/**
 * Response delegation.
 */
//Delegate to this context object
//A getter or setter for delegation methods and attributes
delegate(proto, 'response')
  .method('attachment')
  .method('redirect')
  .method('remove')
  .method('vary')
  .method('set')
  .method('append')
  .method('flushHeaders')
  .access('status')
  .access('message')
  .access('body')
  .access('length')
  .access('type')
  .access('lastModified')
  .access('etag')
  .getter('headerSent')
  .getter('writable');

/**
 * Request delegation.
 */

delegate(proto, 'request')
  .method('acceptsLanguages')
  .method('acceptsEncodings')
  .method('acceptsCharsets')
  .method('accepts')
  .method('get')
  .method('is')
  .access('querystring')
  .access('idempotent')
  .access('socket')
  .access('search')
  .access('method')
  .access('query')
  .access('path')
  .access('url')
  .getter('origin')
  .getter('href')
  .getter('subdomains')
  .getter('protocol')
  .getter('host')
  .getter('hostname')
  .getter('URL')
  .getter('header')
  .getter('headers')
  .getter('secure')
  .getter('stale')
  .getter('fresh')
  .getter('ips')
  .getter('ip');

Because the next page is going to be the most important application.js
So I'm going to talk about a few introduced library source codes.

koa convert

For what? Middleware for transforming koa1 into promise

That's the idea when you see co.==

'use strict'

const co = require('co')
//Introducing co
const compose = require('koa-compose')

module.exports = convert

function convert (mw) {
    //Judge
  if (typeof mw !== 'function') {
    throw new TypeError('middleware must be a function')
  }
  if (mw.constructor.name !== 'GeneratorFunction') {
    // assume it's Promise-based middleware
    return mw
  }
  const converted = function (ctx, next) {
    return co.call(ctx, mw.call(ctx, createGenerator(next)))
  }
  converted._name = mw._name || mw.name
  return converted
}

function * createGenerator (next) {
  return yield next()
}

// convert.compose(mw, mw, mw)
// convert.compose([mw, mw, mw])
// koa-compose will talk about hee hee in the future^
convert.compose = function (arr) {
  if (!Array.isArray(arr)) {
    arr = Array.from(arguments)
  }
  return compose(arr.map(convert))
}
//Oh, My God. The madman also supports retreat.
//It's a wonderful way to go back.
convert.back = function (mw) {
  if (typeof mw !== 'function') {
    throw new TypeError('middleware must be a function')
  }
  if (mw.constructor.name === 'GeneratorFunction') {
    // assume it's generator middleware
    return mw
  }
  const converted = function * (next) {
    let ctx = this
    let called = false
    // no need try...catch here, it's ok even `mw()` throw exception
    yield Promise.resolve(mw(ctx, function () {
        //Make the next call only once
      if (called) {
        // guard against multiple next() calls
        // https://github.com/koajs/compose/blob/4e3e96baf58b817d71bd44a8c0d78bb42623aa95/index.js#L36
        return Promise.reject(new Error('next() called multiple times'))
      }
      called = true
      return co.call(ctx, next)
    }))
  }
  converted._name = mw._name || mw.name
  return converted
}

is-generator-function

'use strict';
//Reducing search references, common optimization methods
var toStr = Object.prototype.toString;
var fnToStr = Function.prototype.toString;
//This regular matches function * but seems to be a bit bug gy
//* function(){} will also be judged true
var isFnRegex = /^\s*(?:function)?\*/;

var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
var getProto = Object.getPrototypeOf;
var getGeneratorFunc = function () { // eslint-disable-line consistent-return
    if (!hasToStringTag) {
        return false;
    }
    try {
        return Function('return function*() {}')();
    } catch (e) {
    }
};
var generatorFunc = getGeneratorFunc();
var GeneratorFunction = generatorFunc ? getProto(generatorFunc) : {};

//From three main points of view.
//One point is function to String
//One point is [object Generator Function] Object to String
//One point is from the prototype (the value of the internal [[Prototype]] attribute)
module.exports = function isGeneratorFunction(fn) {
    if (typeof fn !== 'function') {
        return false;
    }
    if (isFnRegex.test(fnToStr.call(fn))) {
        return true;
    }
    if (!hasToStringTag) {
        var str = toStr.call(fn);
        return str === '[object GeneratorFunction]';
    }
    return getProto(fn) === GeneratorFunction;
};

What a rough writing this time.==
I hope I can finish it at the end.
sry sry sry

Look at all the articles are good!!

Posted by phithe on Sat, 09 Feb 2019 07:42:18 -0800