How does KOA perform common request operations

1. Get Accepts the transmission

Request parameters are placed after the URL

url = 'http://localhost:3000/home? id=12&name=ikcamp'
router.get("/admin/get".async (ctx) => {
  		let ctx_query = ctx.query;
  		console.log("99", ctx_query); --{ id: '12'.name: 'ikcamp'}})Copy the code

The URL is followed by a single parameter

url = 'http://localhost:3000/home/12'
router.get("/users/:id".async (ctx) => {
		console.log(ctx.params) ---{ id: '12' }
        //const { id } = ctx.params
        ctx.body = 'gets the ID as${id}User `;
})
Copy the code

Request parameters are placed in the middle of the URL

url = 'http://localhost:3000/home/12/ikcamp'
// Add the following code
router.get('/home/:id/:name'.async(ctx, next)=>{
    console.log(ctx.params) -- { id: '12'.name: 'ikcamp'}})Copy the code

2. The post value is accepted

Koa-bodyparser NPM install koa-bodyParser --saveconst bodyParser = require("koa-bodyparser");

const app = newKoa(); app.use(bodyParser()); Join before routingconst router = newRouter(); Request parameters in the body such as router.post("/admin/pot".async (ctx) => {
  letquery = ctx.request.body; -- Accept post values;console.log("99", ctx_query);

})
Copy the code

3. Detel accepts the transmission

router.del("/test/deleate".async (ctx, next) => {
  letquery = ctx.query; }) router.del("/users/:id".async (ctx) => {
   const { id } = ctx.params
   ctx.body = 'delete id is${id}User `;
    	})
Copy the code

4. Put Accepts the transmission

router.put("/users/:id".async (ctx) => {
    const { id } = ctx.params
    ctx.body = 'Changes the ID to${id}User `;
})
Copy the code

5. All requests will match all requests

router.all("/users/:id".async (ctx) => {
    ctx.body = ctx.params;
});
Copy the code

Koa uses Sequelize to operate on the database

How do I do paging queries

1, paging fuzzy accurate query

const Sequelize = require("sequelize");
const Op = Sequelize.Op;
const blogPageList = await Blog.findAll({
    order: [['id'.'desc'] by which fields],where: {userId: 1-- Accurate querybrand: {  //brand fuzzy query field
       [Op.like]: ` %${keyword}% `}},limit: pageSize, -- Limit the number of pages per pageoffset: (currentPage-1)*pageSize -- where to start})Copy the code

2, joint table query

const { User, Blog } = require('./model')
const blogListWithUser = await Blog.findAndCountAll({
    order: [['id'.'desc']],include[-- contains the information for the table query {model: User,
        attributes: ['userName'.'nickName'].where: {
          userName: 'zj'}}}])console.log('blogListWithUser: ',
  blogListWithUser.count,
  blogListWithUser.rows.map(blog= > {
    const blogVal = blog.dataValues
    blogVal.user = blogVal.user.dataValues
    return blogVal
  })
  )
Copy the code

3, join table query 2

  const userListWithBlog = await User.findAndCountAll({
    attributes: ['userName'.'nickName'].include: [{model: Blog
      }
    ]
  })
  console.log('userListWithBlog: ',
  userListWithBlog.count,
  userListWithBlog.rows.map(user= > {
    const userVal = user.dataValues
    userVal.blogs = userVal.blogs.map(blog= > blog.dataValues)
    return userVal
  })
  )
Copy the code

Sequelize. Op operators

Sequelize can be used to create the symbolic operator – for more complex comparisons

const Op = Sequelize.Op

[Op.and]: {a: 5}           // and (a = 5)
[Op.or]: [{a: 5}, {a: 6}]  // (a = 5 or a = 6)
[Op.gt]: 6.// id > 6
[Op.gte]: 6.// id >= 6
[Op.lt]: 10.// id < 10
[Op.lte]: 10.// id <= 10
[Op.ne]: 20.// id ! = 20
[Op.eq]: 3./ / = 3
[Op.not]: true./ / it isn't TRUE
[Op.between]: [6.10].// Between 6 and 10
[Op.notBetween]: [11.15].// Not between 11 and 15
[Op.in]: [1.2].// in [1, 2]
[Op.notIn]: [1.2].// Not in [1, 2]
[Op.like]: '%hat'./ / contains' % hat '
[Op.notLike]: '%hat'       // does not contain '%hat'
[Op.iLike]: '%hat'         // contains '%hat' (case insensitive) (PG only)
[Op.notILike]: '%hat'      // does not contain '%hat' (PG only)
[Op.regexp]: '^[h|a|t]'    / / match the regular expression / ~ '^ t] [h | a |' (only MySQL/PG)
[Op.notRegexp]: '^[h|a|t]' // Does not match the regular expression /! ~ ' '^ t] [h | a |' (only MySQL/PG)
[Op.iRegexp]: '^[h|a|t]'    / / ~ * '^ t] [h | a |' (PG) only
[Op.notIRegexp]: '^[h|a|t]' / /! ~ * '^ t] [h | a |' (PG) only
[Op.like]: { [Op.any]: ['cat'.'hat']} // include any array ['cat', 'hat'] - also applies to iLike and notLike
[Op.overlap]: [1.2]       // && [1, 2] (PG array overlap operator)
[Op.contains]: [1.2]      // @> [1, 2] (PG array contains operators)
[Op.contained]: [1.2]     // <@ [1, 2] (PG array contained in operator)
[Op.any]: [2.3]            // Any array [2, 3]::INTEGER (PG only)

[Op.col]: 'user.organization_id' // = 'user'.'organization_id', using the database language-specific column identifier, PG in this example
Copy the code