76 # koa 上下文的实现原理

简介: 76 # koa 上下文的实现原理

上一节实现了 koa 基本逻辑实现以及属性的扩展,下面继续实现上下文的实现

ctx 跟 proto 的关系

ctx.__proto__.__proto__ = proto

MDN:defineGetter

备注: 此特性已弃用,建议使用对象初始化语法或 Object.defineProperty() API 来定义 getter。该方法的行为只针对 Web 兼容性进行了规定,在任何平台上都不需要实现该方法。它可能无法在所有地方正常工作。

MDN:defineSetter

备注: 此特性已弃用,建议使用对象初始化语法或 Object.defineProperty() API 来定义 setter。该方法的行为只针对 Web 兼容性进行了规定,在任何平台上都不需要实现该方法。它可能无法在所有地方正常工作。

  • __defineGetter__() 方法将一个对象的属性绑定到一个函数上,当该属性被访问时,该函数将被调用。
  • __defineSetter__() 方法将一个对象的属性绑定到一个函数上,当该属性被赋值时,该函数将被调用。
__defineGetter__(prop, func)
__defineSetter__(prop, func)

以后使用 ctx 变量时,会很少使用原生的 req 和 res,一般使用的都是 request,reponse,或者直接使用的方式。

下面代码实现:

application.js

const EventEmitter = require("events");
const http = require("http");
const context = require("./context");
const request = require("./request");
const response = require("./response");
console.log("kaimo-koa---->");
class Application extends EventEmitter {
    constructor() {
        super();
        // 防止多个实例共享 context request response 需要进行拷贝
        this.context = Object.create(context);
        this.request = Object.create(request);
        this.response = Object.create(response);
    }
    use(callback) {
        this.callback = callback;
    }
    // 创建一个上下文
    createContext(req, res) {
        // 每次请求都应该是一个全新的 context,需要拷贝
        let ctx = Object.create(this.context);
        // 上下文中有一个 request 对象,是自己封装的
        ctx.request = Object.create(this.request);
        // 上下文中还有一个 req 属性 指代的是原生的 req,自己封装的 request 对象上有 req 属性
        ctx.req = ctx.request.req = req;
        // 上下文中还有一个 response 对象,是自己封装的
        ctx.response = Object.create(this.response);
        // 上下文中还有一个 res 属性 指代的是原生的 res,自己封装的 response 对象上有 res 属性
        ctx.res = ctx.response.res = res;
        return ctx;
    }
    handleRequest(req, res) {
        const ctx = this.createContext(req, res);
        this.callback(ctx);
    }
    listen(...args) {
        const server = http.createServer(this.handleRequest.bind(this));
        server.listen(...args);
    }
}
module.exports = Application;

上下文 context.js

const proto = {
    // get url() {
    //     console.log(this.__proto__.__proto__ === proto);
    //     return this.request.url;
    // },
    // get path() {
    //     return this.request.path;
    // }
};
// 上面一个一个写比较麻烦,可以使用 __defineGetter__ 去实现代理
function defineGetter(target, key) {
    proto.__defineGetter__(key, function () {
        return this[target][key];
    });
}
function defineSetter(target, key) {
    proto.__defineSetter__(key, function (value) {
        this[target][key] = value;
    });
}
defineGetter("request", "url"); // ctx.url => ctx.request.url
defineGetter("request", "path"); // ctx.path => ctx.request.path
defineGetter("request", "query"); // ctx.query => ctx.request.query
defineGetter("response", "body"); // ctx.body => ctx.response.body
defineSetter("response", "body"); // ctx.body => ctx.response.body
module.exports = proto;

response.js

const response = {
    _body: "",
    get body() {
        return this._body;
    },
    set body(value) {
        this._body = value;
    }
};
module.exports = response;

测试 demo.js

const Koa = require("./kaimo-koa");
const app = new Koa();
app.use(async (ctx, next) => {
    ctx.body = "Hello kaimo Koa";
    console.log("url---->", ctx.request.url);
    console.log("path---->", ctx.request.path);
    console.log("query---->", ctx.request.query);
    // ctx.__proto__.__proto__ === proto
    console.log("ctx.url---->", ctx.url);
    console.log("ctx.path---->", ctx.path);
    console.log("ctx.query---->", ctx.query);
    // ctx.body => ctx.response.body
    console.log("ctx.response.body---->", ctx.response.body);
});
app.on("error", (err) => {
    console.log(err);
});
app.listen(3000);

启动服务,访问 http://localhost:3000/kaimo?a=313

nodemon demo.js

目录
相关文章
|
2天前
|
云安全 人工智能 算法
以“AI对抗AI”,阿里云验证码进入2.0时代
三层立体防护,用大模型打赢人机攻防战
1294 3
|
3天前
|
机器学习/深度学习 安全 API
MAI-UI 开源:通用 GUI 智能体基座登顶 SOTA!
MAI-UI是通义实验室推出的全尺寸GUI智能体基座模型,原生集成用户交互、MCP工具调用与端云协同能力。支持跨App操作、模糊语义理解与主动提问澄清,通过大规模在线强化学习实现复杂任务自动化,在出行、办公等高频场景中表现卓越,已登顶ScreenSpot-Pro、MobileWorld等多项SOTA评测。
587 3
|
3天前
|
人工智能 Rust 运维
这个神器让你白嫖ClaudeOpus 4.5,Gemini 3!还能接Claude Code等任意平台
加我进AI讨论学习群,公众号右下角“联系方式”文末有老金的 开源知识库地址·全免费
|
10天前
|
编解码 人工智能 自然语言处理
⚽阿里云百炼通义万相 2.6 视频生成玩法手册
通义万相Wan 2.6是全球首个支持角色扮演的AI视频生成模型,可基于参考视频形象与音色生成多角色合拍、多镜头叙事的15秒长视频,实现声画同步、智能分镜,适用于影视创作、营销展示等场景。
716 4
|
3天前
|
存储 弹性计算 安全
阿里云服务器4核8G收费标准和活动价格参考:u2a实例898.20元起,计算型c9a3459.05元起
现在租用阿里云服务器4核8G价格是多少?具体价格及配置详情如下:云服务器ECS通用算力型u2a实例,配备4核8G配置、1M带宽及40G ESSD云盘(作为系统盘),其活动价格为898.20元/1年起;此外,ECS计算型c9a实例4核8G配置搭配20G ESSD云盘,活动价格为3459.05元/1年起。在阿里云的当前活动中,4核8G云服务器提供了多种实例规格供用户选择,不同实例规格及带宽的组合将带来不同的优惠价格。本文为大家解析阿里云服务器4核8G配置的实例规格收费标准与最新活动价格情况,以供参考。
245 150
|
3天前
|
人工智能 自然语言处理 安全
阿里云万小智AI建站:基础版、标准版、企业版主要功能及价格对比和选择参考
阿里云万小智 AI 建站是一款基于 AI 驱动的自助建站产品,无需代码基础,通过可视化拖拽与 AI 对话即可快速构建高性能、多语言、安全合规的网站。系统深度集成阿里云 ECS、RDS、OSS、CDN、SLB 与 Web 应用防火墙,保障高可用性、数据安全与全球访问速度。其提供多个版本,精准匹配从个人工作室到中大型企业的差异化需求。
238 167