Koa2 development environment

  • Configure ESLint and pre-commit
  • Inspet debugging
  • 404 pages and error pages

Configuration eslint

npm install eslint babel-eslint –save

.eslintrc.json

{
    "parser": "babel-eslint"."env": {
        "es6": true."commonjs": true."node": true
    },
    "rules": {
        "indent": ["error".2]."quotes": [
            "error"."single",
            {
              "allowTemplateLiterals": true}]."semi": [
            "error"."never"]}}Copy the code

.eslintignore

node_modules
test
src/public
Copy the code

To prevent esLint validation from failing, commit code to git repository and install pre-commit

npm install pre-commit –save-dev

Modify the package.json file

Inspet debugging

“dev”: “cross-env NODE_ENV=dev ./node_modules/.bin/nodemon –inspect=9299 bin/www”

jwt

What is the JWT

jwt – json web token

After the user is successfully authenticated, the server returns an encrypted token to the client

Each subsequent request from the client carries a token to indicate the current user identity

The encryption and decryption of the JWT can be resolved by installing KOA-JWT

Install jsonWebToken, encryption tool

jwt vs session

  • To solve: logon & store logon user information
  • JWT user information is encrypted and stored on the client side, independent of cookies and cross-domain
  • Session User information is stored on the server and depends on cookies. By default, user information cannot cross domains

JWT is more suitable for systems with more service nodes, session is more suitable for unified Web services, and Server should strictly manage user information

redis

In-memory database (mysql is hard disk database)

  • Installation:
    • Window: www.runoob.com/redis/redis…
    • mac: brew install redis
  • Start: redis-server, redis-cli
  • Set name ‘cc’
  • The value can be get name
  • Query all values: keys *
  • Exit, exit

The node operating redis

NPM install redis –save

/ * * *@description The redis method get set */

const redis = require('redis')
const { REDIS_CONF } = require('.. /conf/db')

// Create a client
const redisClient = redis.createClient({
6379.127.0. 01.
})
redisClient.on('error'.err= > {
  console.error('redis error', err)
})

/**
 * redis set
 * @param {string} The key key *@param {string} Val values *@param {number} Timeout Indicates the expiration time, in seconds */
function set(key, val, timeout = 60 * 60) {
  if (typeof val === 'object') {
    val = JSON.stringify(val)
  }
  redisClient.set(key, val)
  redisClient.expire(key, timeout)
}

/**
 * redis get
 * @param {string} The key key * /
function get(key) {
  const promise = new Promise((resolve, reject) = > {
    redisClient.get(key, (err, val) = > {
      if (err) {
        reject(err)
        return
      }
      if (val == null) {
        resolve(null)
        return
      }

      try {
        resolve(
          JSON.parse(val)
        )
      } catch (ex) {
        resolve(val)
      }
    })
  })
  return promise
}

module.exports = {
  set,
  get
}
Copy the code

Why is Session good for Redis

  • Session access is frequent and has high performance requirements
  • – Session power outages and data loss (memory damage) are not considered
  • The amount of session data is not too large

Why is redis not appropriate for website data

  • Operation frequency is not too high (compared to session operation)
  • Power outages cannot be lost, they must be preserved
  • Too much data and too high memory cost

How to operate redis,session, and cookie in KOA2

npm i koa-redis koa-generic-session –save

const session = require('koa-generic-session')
const redisStore = require('koa-redis')
/ / the session configuration
app.keys = [SESSION_SECRET_KEY]
app.use(session({
  key: 'weibo.sid'.// Cookie name Defaults to 'koa.sid'
  prefix: 'weibo:sess:'.// the prefix for redis key. The default is' koa:sess: '
  cookie: {
    path: '/'.httpOnly: true.// Can only be modified on the server
    maxAge: 24 * 60 * 60 * 1000  // Expiration time in ms
  },
  store: redisStore({ // Save session data to Redis
    all: `${REDIS_CONF.host}:${REDIS_CONF.port}`}})))Copy the code

Jest unit tests

Using a jest

  • The file must end in.test.js
  • Common assertions
  • Testing the HTTP interface
  1. The installation
npm install jest --save-dev
Copy the code
  1. Modify the package.json file
"scripts": {
	"test": "cross-env NODE_ENV=test jest --runInBand --forceExit --colors"
}
Copy the code
  1. demo
function sum (a, b) {
  return a + b
}
test('10 + 20 = = = 30'.() = > {
  const res = sum(10.20)
  expect(res).toBe(30) // Check whether the values are equal
})
test('10 + 20! = = 40 '.() = > {
  const res = sum(10.20)
  expect(res).not.toBe(40)})Copy the code
  1. Test the HTTP server
npm install supertest --save-dev
Copy the code

server.js

const request = require('supertest')
const server = require('.. /src/app').callback()
module.exports = request(server)
Copy the code

json.test.js

const server = require('./server')

test('JSON interface returns properly'.async() = > {const res = await server.get('/json')
  expect(res.body).toEqual({ // Determine whether objects are equal
    title: 'koa2 json'
  })
  expect(res.body.title).toBe('koa2 json')
})
test('Test post request'.async() = > {const res = await server.post('/login').send({
  	userName: ' '.password: ' '
})
  expect(res.body).toEqual({ // Determine whether objects are equal
    success: true})})Copy the code