navigation

[react] Hooks

[Package 01- Design Pattern] Design Principles and Factory Pattern (Simple Abstract method) Adapter pattern Decorator pattern [Package 02- Design Pattern] Command pattern Share pattern Composition pattern Proxy pattern

[React from Zero practice 01- background] code split [React from zero practice 02- background] permission control [React from zero practice 03- background] custom hooks [React from zero practice 04- background] docker-compose React +egg+nginx+mysql [react from zero practice 05- background

AST Abstract syntax tree [source-webPack02-pre knowledge] Tapable [source-webpack03] Hand-written Webpack-compiler simple compilation process [source] Redux React-redux01 [source] axios [source] koa [source] vuex [source-vue01] data Responsive and initialized render [source-vue02] computed responsive – initialized, access, Update process [source-vue03] Watch listener – Initialize and update [source-vue04] vue. set and vm.$set [source-vue05] vue.extend

Vue.nextTick and vm.$nextTick

[source code -react01] ReactDOM. Render01 [source code -react02] handwritten hook scheduling -useState implementation

[Deployment 01] Nginx [Deployment 02] Docker Deployment Vue Project [Deployment 03] Gitlab-CI

Data Structures and Algorithms 01 binary lookup and sorting

[Delve 01] Execution context [Delve 02] Prototype chain [Delve 03] Inheritance [Delve 04] event loops [Delve 05] Currization partial functions Function memory [Delve 06] Implicit conversions and operators [Delve 07] Browser caching mechanism (HTTP caching mechanism) [Delve 08] front-end security [In Depth 09] Deep copy [in depth 10] Debounce Throttle [in depth 11] Front-end routing [in depth 12] Front-end modularization [in depth 13] Observer mode Publish subscribe mode Bidirectional data binding [in depth 14] Canvas [in depth 15] webSocket [in-Depth 16] Webpack [in-Depth 17] HTTP and HTTPS [in-Depth 18] CSS-Interview [in-Depth 19] Handwritten Promise [In-depth 20] Handwritten Functions [In-depth 21] Data Structures and Algorithms – Binary Lookup and Sorting [In-depth 22] Js and V8 garbage collection mechanisms js design patterns – Proxies, policies, singletons [in-Depth 24] Fiber [In-depth 25] Typescript

[Front-End learning java02-SpringBoot actual] environment configuration and HelloWorld service [front-end learning java02-SpringBoot actual] mybatis + mysql implementation song add, delete, change to check [front-end learning java03-SpringBoot actual] Lombok, log, Deployment [front-end learning Java04 -SpringBoot actual practice] static resources + interceptor + front and back end file upload [front-end learning JAVa05 -SpringBoot actual practice] common notes + Redis to achieve statistical function [front-end learning Java06 -SpringBoot actual practice] injection + Swagger2 3.0 + Unit test JUnit5 [Front-End learning Java07 -SpringBoot practice] IOC scanner + transaction + Jackson [front-end learning Java08 -SpringBoot practice summary 1-7] stage summary [front-end learning Java09 -SpringBoot actual combat] multi-module configuration + Mybatis-plus + single multi-module package deployment [front-end learning Java10 -SpringBoot actual combat] Bean assignment conversion + parameter verification + global exception processing [front-end learning Java11-SpringSecurity] configuration + Memory + database = three ways to implement RBAC [front-end learning Java12-SpringSecurity] JWT [front-end learning Java13-SpringCloud] Eureka + RestTemplate + Zuul + Ribbon

(1) Pre-knowledge

(1) Some words

Note expose statement silent poll stderr standard error noop empty functionCopy the code

(2) Some apis in nodeJs used by KOA

1 http.createserver () koA: koA.listen (3000) -> http.createserver -> server.listen(3000) nodeApi: -http. createServer([options][, requestListener]) - parameter -options: specifies a configuration object, which is optional. -requestListener: Request listener function, optional - return value - new instance of http.Server, return new instance with listen() method on it http://nodejs.cn/api/http.html#http_http_createserver_options_requestlistener - case: HTTP = const the require (" HTTP "); Const server = http.createserver ((req, res) => {// Create a local server to receive data from it // req request // res response res.writehead (200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ // --- res.end() data: 'Hello World! '})); }); server.listen(8000); // --------- server.listen()Copy the code
NextTick function signature: process.nexttick (callback[,...args]) Process.nexttick () takes precedence over each cycle of the Node event loop: - 1. Callback callback - 2. Args Additional parameters to be passed when callback is called 3. Pending callbacks stage - A callback function that performs some system operation, such as (TCP error type) (3) Idle, prepare stage - some preparatory work (4) Poll stage, is a polling queue - 1. If (the polling queue is not empty), take out and execute until (the polling queue is empty) or (reaches the maximum limit of the system) -2. If the setImmediate function is set before, then the state goes to the next phase (check). If the setImmediate function has not been set before, then the current poll phase (wait) -- until a new callback function is added to the poll queue -- leads to (4) phase 1 determination and continues execution -- or the point is reached. The check phase -- setImmediate Mediate (4) Does not mediate (5) The check phase -- setImmediate (5) The check phase -- setImmediate (5) The check phase -- setImmediate (5) The check phase -- setImmediate (5) The check phase -- setImmediate (5) The check phase -- setImmediate (5) The check phase -- setImmediate (5) The check phase -- setImmediate (5) The check phase -- setImmediate Process.nexttick () will poll for nodeJS events (any phase, preferred) - case console.log(1); // Synchronization task setTimeout(() => console.log(2)); SetTimeout (() => console.log(8), 0); NextTick ((n) => console.log(n), 3); SetImmediate (() => console.log(4)) setImmediate(() => mediate(4))) New Promise((resolve) => {console.log(5); // synchronize task resolve(); console.log(7); // Synchronization task}).then((res) => console.log(6)); 1 5 7 3 6 2 8 4 // Synchronous task 1 5 7 // Asynchronous task (micro task) 3 6 // Asynchronous task (macro task) 2 8 4Copy the code

(3) Some APIS of KOA

1 const app = new Koa() -1 - Question: What attributes are on app? - answer: App. Env -- -- -- -- -- -- -- -- -- -- - > environment variables - > default is NODE_ENV or 'development' app. Keys -- -- -- -- -- -- -- -- -- -- > signature cookie key array app. The proxy -- -- -- -- -- -- -- -- -- > Ignore the app.subdomainOffset offset of '. Subdomains' when the real proxy header fields will be trusted, Default is 2 app.proxyipheader -> proxyIpHeader app.maxipcount ----> maximum ips read from proxyIpHeader, default is 0 for unlimited - 2 - question: how to set these properties - answer: there are two ways - 1. Const app = new Koa({proxy: true}) -2. Dynamically set app.proxy = trueCopy the code
2 context-koa context Encapsulates node's 'request' and 'response' objects into a single object - each request creates a 'context' and is referenced as a sink in middleware, Or 'CTX' identifier app.use(async CTX => {CTX; // This is Context ctx.request; // This is koA Request ctx.response; // This is koa Response ctx.req; // Node's 'request' object ctx.res; // Node's 'response' object ctx.state; // The recommended namespace for passing information through middleware and your front-end view ctx.app; });Copy the code

(4) The use of KOA middleware

  • Koa applications
    • The KOA application is an application that contains (A set of middleware functions)objectOrganized and executed in a similar manner
  • The middle price
    • Middleware can accomplish things like:Content negotiation.Cache clearing.Proxy support.redirectEtc.
  • next()
    • When a middleware callnext(), then theFunction to suspendAnd passes control to the defined (Next middleware )
    • When no more middleware is executing downstream, (the stack expands) and (each intermediate key resumes executing) its upstream behavior
Const koa = require("./lib/application.js"); const app = new Koa(); app.use(async (ctx, next) => { console.log(1); await next(); console.log(2); }); app.use(async (ctx, next) => { console.log(3); await next(); console.log(4); }); app.use(async (ctx, next) => { console.log(5); Ctx. body = "Test intermediate execution order "; }); App.listen (1000, () => 'app run 1000') -- When the next() method is executed in a middleware function, the next middleware function is executed recursively. When next() is executed, the rest of the code in the current middleware function is executed in the order of the function call stack // -3. It's the onion modelCopy the code
App -> app property refers to the Koa instance context.req context.res generated by const app = new Koa() context.request context.response context.originalUrl context.state --- app.use(async (ctx, next) => { console.log(1); await next(); console.log(2) })Copy the code

(5) Object.create()

Obejct.create --- const instanceObj = Object.create(prototypeObj) 1. Function: take (parameter object) as (prototype), generate (instance object), the instance object fully inherits the properties and methods of the parameter object 2. Note: The generated instance object (which has no properties or methods of its own) inherits all the properties and methods of the parameter object. Example const a = {name: []} const b = Object.create(a) b // {} b.name === a.name // true Object.getPrototypeof(b) === a // true 4. Simulation of object.create () Function create(obj) {function F(){} // declare a constructor f. protoType = obj // assign the prototype of constructor F to obj, Return new F() // Return instance}Copy the code

(6) how to debug KOA source

  • This project has been configured for debugging and just needs to be executedcnpm run devBreakpoint debuggingindex.jsfile
  • Koa source code analysis – source code debugging warehouse address
Git clone [email protected]:koajs/koa.git 2. 3. Create index.js and write sample code 4. Select 'Run and debug' in 'VScode', create 'launch.json', select 'Node', and configure {"version": "0.2.0", "Configurations ": [{"type": "Node", "request" : "launch", "name" : "start the program," "skipFiles" : [" < node_internals > / * * "], "the program" : "${workspaceFolder}/index.js" } ] } 5. 6. In index.js, click the 'Start Debugging' button on the 'Run and Debug' menu to suspend the breakpointCopy the code

(two) KOA source directory structure description

1. Import file - use 'main' property in package.json to tell the import file is' lib/application.js' 2. -lib /application.js --> koA-related code, That is, new Koa() -lib /context.js ------> is associated with the contxt object -lib /request.js ------> request-related -bli /response.js -----> response associated 3. Dependency -koa-compose ---------> Processing middleware-on-finished ---------> Main purpose: To perform a callback when an HTTP request is closed, completed, or in errorCopy the code

(three) source code main process – middleware

Const Koa = require("./lib/application.js"); const app = new Koa(); app.use(async (ctx, next) => { console.log(1); await next(); console.log(2); }); app.use(async (ctx, next) => { console.log(3); await next(); console.log(4); }); app.use(async (ctx, next) => { console.log(5); Ctx. body = "Test intermediate execution order "; }); App.listen (1000, () => 'app run 1000') -- When the next() method is executed in a middleware function, the next middleware function is executed recursively. When next() is executed, the rest of the code in the current middleware function is executed in the order of the function call stack // -3. It's the onion modelCopy the code
2. Const app = new Koa() app.use() app.listen() class Application extends Emitter {constructor(options) {} // ------------------------------- use use(fn) { this.middleware.push(fn); return this; } // ------------------------------- listen listen(... args) { const server = http.createServer(this.callback()); // Http. createServer is a node native API return server.listen(... args); } // ------------------------------- callback callback() { const fn = compose(this.middleware); const handleRequest = (req, res) => { const ctx = this.createContext(req, res); Return this.handlerequest (CTX, fn); return this.handlerequest (CTX, fn); }; return handleRequest; } // ------------------------------- handleRequest handleRequest(ctx, fnMiddleware) { return fnMiddleware(ctx).then(handleResponse).catch(onerror); FnMiddleware (CTX)}}Copy the code
3 fnMiddleware(CTX) - fnMiddleware(CTX) is the fn returned by const fn = compose(this.middleware) -compose is dependent on the library 'koa-compose', The specific code is as follows -- // ------------------------------------------------------------------------------------------------------------------- Compose // - parameters // - array of intermediate values, each middleware must be a function // - return value // - return a function function compose(middleware) {if (! Array.isArray(middleware)) throw new TypeError("Middleware stack must be an array!" ); // The argument must be an array for (const fn of middleware) {if (typeof fn! == "function") throw new TypeError("Middleware must be composed of functions!" ); } /** * @param {Object} context * @return {Promise} * @api public */ return function (context, next) { // last called middleware # let index = -1; return dispatch(0); Function dispatch(I) {// call: dispatch(0) if (i <= index) { return Promise.reject(new Error("next() called multiple times")); // dispatch(0) : (0 <=-1)} index = I; // 1 // i = 0 --> index = i = 0 let fn = middleware[i]; // 1 // Middleware [0] If (I === middleware.length) fn = next; Dispatch () --> fn=next=undefined --> return promise.resolve (), // -- next does not exist, Return promise.resolve () // next(context, dispatch. Bind (null, I +1)) // fn does not have if (! fn) return Promise.resolve(); Resolve (fn(context, dispatch.bind(null, I + 1))); // 1 // Structure of middleware function // app.use(async (CTX, next) => {... }) // async (ctx, next) => {... } // 2 // fn(context, dispatch.bind(null, I +1)) --> next() --> I +1 is the next middleware} catch (err) {return promise.reject (err); }}}; }Copy the code
4 Combing middleware - Call order: App.listen () --> Callback () --> handleRequest() --> Middleware FN (CTX).then(handleResponse).catch(onerror) -fnmiddleware = compose(this.middleware) = function (context, 1. FnMiddleware (CTX). Then (handleResponse). Catch (onError) 2. next) => dispatch(0)).then(handleResponse).catch(onerror) 3. dispatch(0).then(handleResponse).catch(onerror) 4. Promise.resolve(middlewareFn0(context, dispatch.bind(null,1))) 5. Promise.resolve(async(ctx, dispatch) => {... dispatch(1) ... }) 6. Const [fn1, fn2, fn3] = this. Middleware () const fnMiddleware = function(context, next) { return Promise.resolve(fn1(context, function next1() { return Promise.resolve(fn2(context, Resolve (fn(context, dispatch.bind(null, I + 1))); // Return promise.resolve (fn(context, dispatch.bind(null, I + 1))); Resolve (fn3(context, function next3() {return promise.resolve (context, function next3() { Resolve ()}))}))}))} 7. FnMiddleware () performs the final state as follows - 7.1 app.use(async (CTX, next) => { console.log(1); await next(); console.log(2); }); app.use(async (ctx, next) => { console.log(3); await next(); console.log(4); }); app.use(async (ctx, next) => { console.log(5); Ctx. body = "Test intermediate execution order "; }); Resolve (// fn1() console.log(1) await promise.resolve (// next() // fn2()) console.log(3) await Promise.resolve( // next() // fn3() console.log(5) return Promise.resolve() ) console.log(4) ) console.log(2) ) .then(handleResponse) .catch(onerror) // 13542Copy the code

Source code analysis warehouse address

  • Koa source code analysis – warehouse address
  • Koa source code analysis – mind mapping

data

Koa official website koa.bootcss.com/ KOA source code analysis juejin.cn/post/699867… Sichuan juejin god. Cn/post / 684490…