get 方法應該接收一個 userid,它具有在 stcok.json 檔案中定義的初始點總數和在另一個檔案中定義的一些事務。
下面是股票 json 的示例條目
[
{ "user": "abcdef", "points": 678 },
{ "user": "gfdsert", "points": 8414 }
]
另一個檔案,事務 json 檔案,其中為用戶 ID 記錄了許多事務。如果交易中的積分(pts)是“加”型別,則應從初始積分中扣除,如果是“減”,則應添加積分。
[
{ "user": "abcdef", "type": "plus", "pts": 8 },
{ "user": "dfgvhj", "type": "plus", "pts": 4 },
{ "user": "gfdsert", "type": "minus", "pts": 5 },
{ "user": "gfdsert", "type": "plus", "pts": 3 },
{ "user": "lkjhgf", "type": "plus", "pts": 6 }
]
我需要幫助以有效的方式閱讀這兩個檔案。我正在同步閱讀這篇文章,我知道這不是閱讀檔案的好方法。當用戶 ID 的兩個檔案中都存在條目時,一切正常
此外,我無法在錯誤路徑期間使其正常作業。當檔案中不存在條目時,我總是偶然發現點陣列和事務陣列的“未定義”錯誤。如果用戶不在兩個檔案中,它應該拋出錯誤“找不到用戶”。但是,用戶可以出現在任何一個或兩個檔案中。如果用戶不在股票 json 檔案中,則初始點應視為零。類似地,用戶可能有也可能沒有任何交易。
我下面的代碼---我試過的
let pointlist = JSON.parse(fs.readFileSync("./stock1.json", "utf8"));
let transactionlist = JSON.parse(fs.readFileSync("./transactions1.json", "utf8"));
// Definition of the callback function
const callback = (err, points, positiveTransactions, negativeTransactions) => {
if(err) {
return `user with given id ${err} not found`;
}
else {
let sum = positiveTransactions.reduce(function (previousValue, currentValue) {
return previousValue currentValue.pts
}, 0)
let diff = negativeTransactions.reduce(function (previousValue, currentValue) {
return previousValue currentValue.pts
}, 0)
let value = points.points - sum diff
return "Here is the number of remaining points: " value;
}
}
// Passing userId and callback function as parameter
const findPoints = (userId, callbackFunction) => {
let points = pointlist.find(function(userValue) {
return userValue.user == userId;
});
let positiveTransactions = transactionlist.filter(function(userValue) {return userValue.user == userId && userValue.type == 'plus' });
let negativeTransactions = transactionlist.filter(function(userValue) {return userValue.user == userId && userValue.type == 'minus' });
// user not found
if(typeof points === 'undefined' && typeof positiveTransactions === 'undefined' && typeof negativeTransactions === 'undefined') {
return callbackFunction(userId, false, false, false);
}
else { // user found
return callbackFunction(null, points, positiveTransactions, negativeTransactions);
}
}
const getPoints = (req, res)=>{
// Sending back the response to the server
res.status(200).send(findPoints(req.query.userId, callback));
}
app.get('/getName', getPoints);
app.listen(8000, 'localhost', function () {
console.log('Server Listening');
});
uj5u.com熱心網友回復:
我無法弄清楚你做錯了什么,所以我重構以使其更清晰并使其正常作業。我還嘗試添加注釋來解釋我的想法。稍微嘗試一下,并隨時提出您可能有的任何問題。我也沒有改變你閱讀檔案的方式。readFileSync如果您可以確信不會耗盡記憶體(只有在您的串列非常大時才會發生這種情況),那么IMO就可以了。那時,我會考慮將檔案作為流讀取。
const express = require('express')
const app = express()
// Read files here. I'm skipping that part.
const stock = [
{ "user": "mike", "points": 678 },
{ "user": "john", "points": 8414 }
]
const transactions = [
{ "user": "mike", "type": "plus", "pts": 8 },
{ "user": "joe", "type": "plus", "pts": 4 },
{ "user": "john", "type": "minus", "pts": 5 },
{ "user": "john", "type": "plus", "pts": 3 },
{ "user": "luke", "type": "plus", "pts": 6 }
]
// Better to name your endpoints after nouns, and leave the verb out of it since it's redundant (app.get("/GETpoints"))
app.get('/points', (req, res) => {
const userId = req.query.userId
if (!req.query.userId) {
return res.status(404).json({ message: 'userId query param must be provided' })
}
// Make sure both of these are arrays since we will call array methods on them later
// Note: 500 means "Internal Server Error" and it's common to send JSON instead of plain strings
if (!Array.isArray(stock) || !Array.isArray(transactions)) {
return res.status(500).json({ message: 'Error in file data. Expected arrays. Check stock and transactions files.' })
}
// Find the matching user in the stock file
const stockUser = stock.find(userObject => {
return userObject.user === userId
})
// Find the user's transactions
const userTransactions = transactions.filter(transaction => {
return transaction.user === userId
})
// Handle the case where user is missing from both files
if (!stockUser && userTransactions.length === 0) {
return res.status(404).json({ message: 'User not found' })
}
// Default to 0 if stockUser.points is falsy (null, undefined, false, 0, empty string)
// I'm using something called "optional chaining" here to make sure stockUser.points safely fails if
// stockUser is null or undefined. You can read more about it, it's very useful.
const startingPoints = stockUser?.points || 0
let points = startingPoints
// I used simple if/else instead of reduce as a personal preference since I find it more readable
userTransactions.forEach(transaction => {
if (transaction.type === 'plus') {
points = transaction.pts
} else if (transaction.type === 'minus') {
points -= transaction.pts
}
})
return res.status(200).json({userId: userId, points: points})
});
app.listen(8000, () => {
console.log('Server Listening');
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/369848.html
標籤:javascript 节点.js 表达 异步
下一篇:在Blazor中,`awaitTask.Run(StateHasChanged)`和`awaitInvokeAsync(StateHasChanged)`之間有什么區別?
