1.0.3 • Published 2 years ago

koa5gouwuche v1.0.3

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

gitter NPM version build status Test coverage OpenCollective Backers OpenCollective Sponsors PR's Welcome

Expressive HTTP middleware framework for node.js to make web applications and APIs more enjoyable to write. Koa's middleware stack flows in a stack-like manner, allowing you to perform actions downstream then filter and manipulate the response upstream.

Only methods that are common to nearly all HTTP servers are integrated directly into Koa's small ~570 SLOC codebase. This includes things like content negotiation, normalization of node inconsistencies, redirection, and a few others.

Koa is not bundled with any middleware.

Installation

Koa requires node v7.6.0 or higher for ES2015 and async function support.

$ npm install koa

Hello Koa

Getting started

  • Kick-Off-Koa - An intro to Koa via a set of self-guided workshops.
  • Workshop - A workshop to learn the basics of Koa, Express' spiritual successor.
  • Introduction Screencast - An introduction to installing and getting started with Koa

Middleware

Koa is a middleware framework that can take two different kinds of functions as middleware:

  • async function
  • common function

Here is an example of logger middleware with each of the different functions:

async functions (node v7.6+)

const Router = require("koa2-router");
const CartController = require("./controller/cart");

const router = new Router();

router.post("/cart/add", CartController.AddCart);
router.put("/cart/update", CartController.UpdataCartCount);
router.delete("/cart/del", CartController.CartDelete);
router.get("/cart/show", CartController.CartShow);
router.get("/cart/zprice", CartController.CartZprice);


module.exports = router;
router.js

Common function

// Middleware normally takes two parameters (ctx, next), ctx is the context for one request,
// next is a function that is invoked to execute the downstream middleware. It returns a Promise with a then function for running code after completion.

const CartService = require("../service/cart");
const AddCart = async (ctx) => {
  const userdata = ctx.state.user.data;
  ctx.request.body.userid = userdata.id;
  let CheckCart = await CartService.CheckCart(ctx.request.body);
  if (CheckCart.length > 0) {
    let UpdateCart = await CartService.UpdateCart(ctx.request.body);
    if (UpdateCart.affectedRows <= 0) {
      return (ctx.body = {
        code: 403,
        message: "tianjia shibai",
      });
    }
  } else {
    let AddCart = await CartService.AddCart(ctx.request.body);
    if (AddCart.affectedRows <= 0) {
      return (ctx.body = {
        code: 403,
        message: "tianjia shibai",
      });
    }
  }
  return (ctx.body = {
    code: 200,
    message: "tianjia chengong",
  });
};

const CartShow = async (ctx) => {
  const userdata = ctx.state.user.data;
  ctx.query.userid = userdata.id;
  let res = await CartService.CartShow(ctx.query);
  if (res.count >= 0) {
    return (ctx.body = {
      code: 200,
      message: "chaxun chenggong",
      data: res,
    });
  }
};

const CartDelete = async (ctx) => {
  let res = await CartService.CartDelete(ctx.query);
  if (res.affectedRows > 0) {
    return (ctx.body = {
      code: 200,
      message: "shanchu chengong",
    });
  } 
};

const UpdataCartCount = async (ctx) => {
  let res = await CartService.UpdataCartCount(ctx.request.body);
  if (res.affectedRows > 0) {
    return (ctx.body = {
      code: 200,
      message: "xiugai chengong",
    });
  } 
};

const CartZprice = async (ctx) => {
  const userdata = ctx.state.user.data;
  ctx.query.userid = userdata.id;
  let res = await CartService.CartZprice(ctx.query);
  if (res.length > 0) {
    return (ctx.body = {
      code: 200,
      message: "jisuan chenggong",
      data: res,
    });
  } 
};
module.exports = {
  AddCart,
  CartShow,
  CartDelete,
  UpdataCartCount,
  CartZprice,
};


controller/cart.js

Koa v1.x Middleware Signature

The middleware signature changed between v1.x and v2.x. The older signature is deprecated.

Old signature middleware support will be removed in v3

Please see the Migration Guide for more information on upgrading from v1.x and using v1.x middleware with v2.x.

Context, Request and Response

Each middleware receives a Koa Context object that encapsulates an incoming http message and the corresponding response to that message. ctx is often used as the parameter name for the context object.

Koa provides a Request object as the request property of the Context.
Koa's Request object provides helpful methods for working with http requests which delegate to an IncomingMessage from the node http module.

Here is an example of checking that a requesting client supports xml.

const query = require("../db/query");

const CheckCart = async (params) => {
  let sql = `select * from cart where userid = ${params.userid} and shopid = ${params.shopid}`;
  return await query(sql);
};
const UpdateCart = async (params) => {
  let sql = `update cart set count = count + ${params.count}  where userid = ${params.userid} and shopid = ${params.shopid}`;
  return await query(sql);
};
const AddCart = async (params) => {
  let sql = `insert into cart (userid,shopid,count) values (${params.userid},${params.shopid},${params.count})`;
  return await query(sql);
};

const CartShow = async (params) => {
  let sql = `select a.id,b.name,b.price,b.price*a.count zprice,a.count from cart a join shop b on a.shopid = b.id where userid = ${params.userid}`;
  if (params.name) {
    sql += ` and b.name like '%${params.name}%'`;
  }
  let count = (await query(sql)).length;
  sql += ` limit ${(params.page - 1) * params.size},${params.size}`;
  let cartdata = await query(sql);
  return { count, cartdata };
};

const CartDelete = async (params) => {
  let sql = `delete from cart where id in (${params.ids})`;
  return await query(sql);
};

const UpdataCartCount = async (params) => {
  let sql = `update cart set count=`;
  if (params.data) {
    sql += ` count-1`;
  } else {
    sql += ` count+1`;
  }
  sql += ` where id = ${params.id}`;
  return await query(sql);
};
const CartZprice = async (params) => {
  let sql = `select sum(a.count * b.price) zprice from cart a join shop b on a.shopid = b.id where userid = ${params.userid} and a.id in (${params.ids})`;
  return await query(sql);
};
module.exports = {
  CheckCart,
  UpdateCart,
  AddCart,
  CartShow,
  CartDelete,
  UpdataCartCount,
  CartZprice,
};


service/cart.js

Koa provides a Response object as the response property of the Context.
Koa's Response object provides helpful methods for working with http responses which delegate to a ServerResponse .

Koa's pattern of delegating to Node's request and response objects rather than extending them provides a cleaner interface and reduces conflicts between different middleware and with Node itself as well as providing better support for stream handling. The IncomingMessage can still be directly accessed as the req property on the Context and ServerResponse can be directly accessed as the res property on the Context.

Here is an example using Koa's Response object to stream a file as the response body.

var jwt = require("jsonwebtoken");

const signtoken = async (userdata) => {
  return await jwt.sign(
    {
      data: userdata,
    },
    "asdfgh",
    {
      expiresIn: "2h",
    }
  );
};

module.exports = { signtoken };
extend/help.js
const Redis = require("ioredis");
const redis = new Redis();
module.exports = redis;
extend/redis.js

The Context object also provides shortcuts for methods on its request and response. In the prior examples, ctx.type can be used instead of ctx.response.type and ctx.accepts can be used instead of ctx.request.accepts.

For more information on Request, Response and Context, see the Request API Reference, Response API Reference and Context API Reference.

Koa Application

The object created when executing new Koa() is known as the Koa application object.

The application object is Koa's interface with node's http server and handles the registration of middleware, dispatching to the middleware from http, default error handling, as well as configuration of the context, request and response objects.

Learn more about the application object in the Application API Reference.

Documentation

Troubleshooting

Check the Troubleshooting Guide or Debugging Koa in the general Koa guide.

Running tests

$ npm test

Reporting vulnerabilities

To report a security vulnerability, please do not open an issue, as this notifies attackers of the vulnerability. Instead, please email dead_horse, jonathanong, and niftylettuce to disclose.

Authors

See AUTHORS.

Community

Job Board

Looking for a career upgrade?

Backers

Support us with a monthly donation and help us continue our activities.

Sponsors

Become a sponsor and get your logo on our README on Github with a link to your site.

License

MIT

1.0.3

2 years ago

1.0.1

2 years ago