【发布时间】:2020-08-15 23:23:45
【问题描述】:
我找到了关于的教程 Designing a clean REST API with Node.js (Express + Mongo)
github中的项目。
但问题是我没有理解路由的概念。
误解的部分是如何将
httpRequest数据传递给contact-endpoint模块中的handle方法?
因为handle方法在这里export default function makeContactsEndpointHandler({ contactList }) { return async function handle(httpRequest) {
这是项目的index:
import handleContactsRequest from "./contacts";
import adaptRequest from "./helpers/adapt-request";
app.all("/contacts", contactsController);
app.get("/contacts/:id", contactsController);
function contactsController(req, res) {
const httpRequest = adaptRequest(req);
handleContactsRequest(httpRequest)
.then(({ headers, statusCode, data }) =>
res.set(headers).status(statusCode).send(data)
)
.catch((e) => res.status(500).end());
}
这是adaptRequest:
export default function adaptRequest (req = {}) {
return Object.freeze({
path: req.path,
method: req.method,
pathParams: req.params,
queryParams: req.query,
body: req.body
})
}
这是handleContactsRequest 模块:
import makeDb from "../db";
import makeContactList from "./contact-list";
import makeContactsEndpointHandler from "./contacts-endpoint";
const database = makeDb();
const contactList = makeContactList({ database });
const contactsEndpointHandler = makeContactsEndpointHandler({ contactList });
export default contactsEndpointHandler;
这是contact-endpoint 模块的一部分:
export default function makeContactsEndpointHandler({ contactList }) {
return async function handle(httpRequest) {
switch (httpRequest.method) {
case "POST":
return postContact(httpRequest);
case "GET":
return getContacts(httpRequest);
default:
return makeHttpError({
statusCode: 405,
errorMessage: `${httpRequest.method} method not allowed.`,
});
}
}
【问题讨论】:
标签: node.js express node-modules