码迷,mamicode.com
首页 > 其他好文 > 详细

koa-Context

时间:2019-09-28 10:37:49      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:一个   method   exports   web   not   log   uil   zh-cn   SHH   

Context

context对象是我们使用koa十分重要的一个环节,在Application中的createContext(req, res)方法里,在context对象上挂在了很多对象,koa的requestresponse对象、node原生的reqres对象、app对象、originalUrlcookiesacceptstate`。它提供了处理请求与响应的所有接口,下面来看看它的源码。

Context prototype

1
2
3
4
5
6
7

* Context prototype.
*/

const proto = module.exports = {
...
};

首先,它的注释写的是Context prototype,这个文件导出的是一个原型对象,context是通过Object.create(context)创建出来的。(Object.create()

其他方法

其他方法比较简单,比如throw()onerror()等,这里就不再多说。

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
throw(...args) {
throw createError(...args);
},
onerror(err) {
// don't do anything if there is no error.
// this allows you to pass `this.onerror`
// to node-style callbacks.s allows you to pass `this.onerror`
// to node-style callbacks.
if (null == err) return;

if (!(err instanceof Error)) err = new Error(util.format('non-error thrown: %j', err));

let headerSent = false;
if (this.headerSent || !this.writable) {
headerSent = err.headerSent = true;
}

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

// nothing we can do here other
// than delegate to the app-level
// handler and log.
if (headerSent) {
return;
}

const { res } = this;

// first unset all headers
if (typeof res.getHeaderNames === 'function') {
res.getHeaderNames().forEach(name => res.removeHeader(name));
} else {
res._headers = {}; // Node < 7.7
}

// then set those specified
this.set(err.headers);

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

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

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

// respond
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);
}

delegate

context的精髓主要在于代理了request和response的一些常用方法,看代码:

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
const delegate = require('delegates');

* Response delegation.
*/

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');

这样就为程序员提供了更简洁的调用方式。主要实现方法在delegates库里,咱们来瞅瞅。

delegates

这是一个Nodejs 方法和属性 代理工具库。

构造函数

1
2
3
4
5
6
7
8
9
10
module.exports = Delegator;
function (proto, target) {
if (!(this instanceof Delegator)) return new Delegator(proto, target);
this.proto = proto;
this.target = target;
this.methods = [];
this.getters = [];
this.setters = [];
this.fluents = [];
}

这种构造函数相当于一个工厂方法,快速创建一个Delegator对象。有一个成员属性,proto是代理对象,target是被代理的对象,methods数组用来存放方法名,getterssetters数组用来存放属性的accessors,fluents数组用来存放属性。
defineGetterdefineSetter

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
Delegator.prototype.method = function(name){
var proto = this.proto;
var target = this.target;
this.methods.push(name);

proto[name] = function(){
return this[target][name].apply(this[target], arguments);
};

return this;
};

Delegator.prototype.access = function(name){
return this.getter(name).setter(name);
};

Delegator.prototype.getter = function(name){
var proto = this.proto;
var target = this.target;
this.getters.push(name);

proto.__defineGetter__(name, function(){
return this[target][name];
});

return this;
};

Delegator.prototype.setter = function(name){
var proto = this.proto;
var target = this.target;
this.setters.push(name);

proto.__defineSetter__(name, function(val){
return this[target][name] = val;
});

return this;
};

Delegator.prototype.fluent = function (name) {
var proto = this.proto;
var target = this.target;
this.fluents.push(name);

proto[name] = function(val){
if ('undefined' != typeof val) {
this[target][name] = val;
return this;
} else {
return this[target][name];
}
};

return this;
};

原文:大专栏  koa-Context


koa-Context

标签:一个   method   exports   web   not   log   uil   zh-cn   SHH   

原文地址:https://www.cnblogs.com/petewell/p/11601653.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!