2 Jan 2023 to 9 Jan 2023
Weekly forecast
- Work on backend cms
I will persist until I succeed —by OG Mandino
express.Router
Use the express.Router class to create modular, mountable route handlers. A Router instance is a complete middleware and routing system; for this reason, it is often referred to as a “mini-app”.
1
2
3
4
5
6
7
8
9
const taskRouter = express.Router();
// 缺省tasks directory
taskRouter.get("", getAllTasks);
taskRouter.get("/:id", getTaskById);
taskRouter.post("", newTasks);
taskRouter.put("/:id", updateById);
taskRouter.delete("/:id", deleteById);
module.exports = taskRouter;
- so taskRouter is like a mini-app, because on app, we can also register the node(endpoint) and handler/middleware-function to it, only need to expose it by module.exports = taskRouter.
- as
taskRouter
is a module(function), so it can be used inapp.use('/tasks',taskRouter)
.
create a new data to document in mongoDB
1
2
const newUser = new userModel(userObj);
await newUser.save();
- userObj must be a object that meet the requirement from the userModel schema.
middleware
- cors
- dotenv
- change of dotenv file request a restart of node server, with command
rs
in console.
- change of dotenv file request a restart of node server, with command
- morgan
log the request origin, request time and so on
1
2
const morgan = require("morgan");
app.use(morgan());
helmet
protect the header
- check with postman, header section.’x-powered-by’ info will be covered.(server normally not update after deploy, with newer version released, the bugs in the previous version will become public known bugs.)
- winston
- control level, output directory/database/logger library.
mongoose findOneAndUpdate()
- As the name implies, findOneAndUpdate() finds the first document that matches a given filter, applies an update, and returns the document. By default, findOneAndUpdate() returns the document as it was before update was applied.
You should set the
new
option totrue
to return the document afterupdate
was applied.
findOneAndX and findByIdAndX functions support limited validation. You can enable validation by setting the
runValidators
option.If you need full-fledged validation, use the traditional approach of first retrieving the document. 用了 findAnd 的话,validator 会不好使.想要 validator 要用传统方法,save()
1
2
3
const doc = await Model.findById(id);
doc.name = "jason bourne";
await doc.save();
数据验证可以单独写,写一次,前后端都可以用.
永远不要相信客户端发送过来的数据,一定要自己验证一遍!!! important to validate the data from frontEnd
regex101 can interpret the regex and test it, handy website.
use Joi for validation
- two steps validation:
- a schema is constructed
- the value is validated against the defined schema:
1
2
const schema = Joi.string().email();
const validation = schema.validate(email);
error middleware
- express async error will auto create one error handler.
- if ‘express async error’ package is used in express 4, error middleware must be registered after the route handler(s).
- index.js(error md) should be placed at the bottom of the error middleware chain to send 500 error, and should record error and user behavior if possible for troubleshooting.
有写 next() 一定要加 return, in error middleware, return should be added to next().
customized schema method
- customized schema methods with the cod, and then all instances of mySchema has their own method called hashPassword.
remember customized schema methods need to be registered before model forming.
1
2
3
4
5
mySchema.methods.hashPassword = async function () {
this.password = await bcrypt.hash(this.password, 12);
};
module.exports = model("yourdocument", mySchema);
// after doing so, all instances of schemaA has their own method called hashPassword.
Do not declare methods using ES6 arrow functions (=>). Arrow functions explicitly prevent binding this, so your method will not have access to the document and the above examples will not work.
token generate and validate
- generate token when user try to register or login
- verify token using the middleware authGuard.
status(401)meaning unauthorized
bcrypt hash and compare is async
- need add async and await 不然会出错
test Jest
- 函数 B.toHaveBeenCalled(参数 A)表示测试的时候,参数 A 会被传入函数 B,如果传入的不是 A,则会报错,这个语句在 res.status(201).json({})时候很有用.
callback hell
- nested callback, one depends on the other. develops vertically instead of horizontally.