Directly use folder name as _id in Quest

This commit is contained in:
wancat committed 2023-07-20 16:25:10 +08:00
1 parent 0d9b068678
commit 3e9e14399a
4 files changed
+21 -30

No files matched your search

@@ -4,7 +4,7 @@ export async function getQuests(req, res) {
const quests = await Quest.find({}).sort({ order: 1 })
res.json(
quests.map(({ name, title, order, _id }) => ({
id: _id,
_id,
name,
title,
order,
@@ -13,8 +13,8 @@ export async function getQuests(req, res) {
}
export async function getQuestDetail(req, res) {
const { name } = req.params
const quest = await Quest.findOne({ name })
const { id } = req.params
const quest = await Quest.findById(id)
if (!quest) {
res.status(404).json({ message: 'Quest not found.' })
return
+1 -1
View File
@@ -4,6 +4,6 @@ import * as questController from '../controllers/questController.js'
const router = Router()
router.get('/', questController.getQuests)
router.get('/:name', questController.getQuestDetail)
router.get('/:id', questController.getQuestDetail)
export default router
+1 -1
View File
@@ -3,7 +3,7 @@ import { model, Schema } from 'mongoose'
const Quest = model(
'Quest',
new Schema({
name: String,
_id: String,
title: String,
order: Number,
content: String,
+16 -25
View File
@@ -12,12 +12,12 @@ const marked = new Marked({
const questDirectory = path.join(process.cwd(), 'quests')
async function parseQuests() {
export default async function loadAndUpdateQuests() {
const questNames = await fs.readdir(questDirectory)
const quests = Promise.all(
questNames.map(async (name) => {
const fullPath = path.join(questDirectory, name, 'README.md')
questNames.map(async (id) => {
const fullPath = path.join(questDirectory, id, 'README.md')
try {
// Read and parse the README.md file.
@@ -31,14 +31,20 @@ async function parseQuests() {
const { title, order } = metadata
return {
name,
title,
order,
content: htmlContent,
}
return Quest.findByIdAndUpdate(
id,
{
_id: id,
title,
order,
content: htmlContent,
},
{
upsert: true,
}
)
} catch (error) {
console.error(`Error parsing quest ${name}:`, error)
console.error(`Error parsing quest ${id}:`, error)
throw error
}
})
@@ -46,18 +52,3 @@ async function parseQuests() {
return quests
}
async function updateQuests(quests) {
Promise.all(
quests.map((quest) => {
return Quest.findOneAndUpdate({ name: quest.name }, quest, {
upsert: true,
})
})
)
}
export default async function loadAndUpdateQuests() {
const quests = await parseQuests()
await updateQuests(quests)
}