【发布时间】:2020-08-29 05:49:39
【问题描述】:
我正在用await cartsRepo.create({ items: [] }); 定义cart 变量,但我继续在cart 上获得undefined。
我的猜测是该请求永远不会解决,因此它永远不会落入if 条件,但不确定。
部分错误是未处理的承诺拒绝,因此我将其全部放入 try/catch 块中,但我仍然在 cart 上收到 undefined。
const express = require("express");
const cartsRepo = require("../repositories/carts");
const router = express.Router();
// Receive a post request to add an item to a cart
router.post("/cart/products", async (req, res) => {
console.log(req.body.productId);
// Figure out the cart!
try {
let cart;
if (!req.session.cartId) {
// // we dont have a cart, we need to create one,
// // and store the cart id on the req.session.cartId property
cart = await cartsRepo.create({ items: [] });
req.session.cartId = cart.id;
} else {
// // We have a cart! Lets get it from the repository
cart = await cartsRepo.getOne(req.session.cartId);
}
const existingItem = cart.items.find(
(item) => item.id === req.body.productId
);
if (existingItem) {
// increment quantity and save cart
existingItem.quantity++;
} else {
// add new product id to items array
cart.items.push({ id: req.body.productId, quantity: 1 });
}
await cartsRepo.update(cart.id, {
items: cart.items,
});
} catch (error) {
console.log(error);
}
res.send("Product added to cart");
});
// Receive a get request to show all items in cart
// Receive a post request to delete an item from a cart
module.exports = router;
缺少的部分可能是我没有使用数据库,而是创建了这个 repository.js 文件,我的所有数据都存储在一些 json 文件中:
const fs = require("fs");
const crypto = require("crypto");
module.exports = class Repository {
constructor(filename) {
if (!filename) {
throw new Error("Creating a repository requires a filename");
}
this.filename = filename;
try {
fs.accessSync(this.filename);
} catch (error) {
fs.writeFileSync(this.filename, "[]");
}
}
async create(attrs) {
attrs.id = this.randomId();
const records = await this.getAll();
records.push(attrs);
await this.writeAll(records);
}
async getAll() {
return JSON.parse(
await fs.promises.readFile(this.filename, {
encoding: "utf8"
})
);
}
async writeAll(records) {
// write the updated 'records' array back to this.filename
await fs.promises.writeFile(
this.filename,
JSON.stringify(records, null, 2)
);
}
randomId() {
return crypto.randomBytes(4).toString("hex");
}
async getOne(id) {
const records = await this.getAll();
return records.find(record => record.id === id);
}
async delete(id) {
const records = await this.getAll();
const filteredRecords = records.filter(record => record.id !== id);
await this.writeAll(filteredRecords);
}
async update(id, attrs) {
const records = await this.getAll();
const record = records.find(record => record.id === id);
if (!record) {
throw new Error(`Record with id ${id} not found`);
}
// record === { email: "test@test.com" }
// attrs === { password: 'mypassword' }
// so attrs is copied over to record object to result in { email: "test@test.com", password: 'mypassword' }
Object.assign(record, attrs);
// take array of records and write it back to JSON file
await this.writeAll(records);
}
async getOneBy(filters) {
const records = await this.getAll();
// iterate through the collection of records - for/of loop because iterating through array
for (let record of records) {
let found = true;
// iterate through all key/value pairs of the filters object - for/in because iterating through object
for (let key in filters) {
// receive every key inside the object and can look at the value inside of object with filters[key]
// it means email or password at filters is the same as email password on record
if (record[key] !== filters[key]) {
// if email and password between filters and record do not match then...
found = false;
}
}
// record was found because filters object key/value pairs and record are same
if (found) {
return record;
}
}
}
};
【问题讨论】:
-
听起来像 cartsRepo 没有返回你认为应该的样子。
标签: javascript node.js express async-await