Load and update quests on startup

This commit is contained in:
wancat committed 2023-07-20 15:08:47 +08:00
1 parent b2173d180d
commit 3637d41529
3 files changed
+33 -7

No files matched your search

+2
View File
@@ -7,6 +7,7 @@ import swaggerUI from 'swagger-ui-express'
import socketServer from './api/socket.js'
import connectDB from './db.js'
import apiRouter from './api/routes/index.js'
import loadAndUpdateQuests from './utils/quest.js'
async function main() {
const port = 3000
@@ -14,6 +15,7 @@ async function main() {
const server = http.createServer(app)
socketServer(server)
await connectDB()
await loadAndUpdateQuests()
const file = await fs.readFile('./swagger.yaml', 'utf8')
const swaggerDocument = YAML.parse(file)
+4 -3
View File
@@ -1,12 +1,13 @@
import { model } from 'mongoose'
import { Schema } from 'yaml'
import { model, Schema } from 'mongoose'
const Quest = model(
'Quest',
new Schema(
{
name: String,
description: String,
title: String,
order: Number,
content: String,
},
{ timestamp: true }
)
+27 -4
View File
@@ -1,8 +1,15 @@
import fs from 'fs/promises'
import path from 'path'
import { marked } from 'marked'
import { Marked } from 'marked'
import yaml from 'yaml'
import Quest from '../models/quest.js'
const marked = new Marked({
mangle: false,
headerIds: false,
})
const questDirectory = path.join(process.cwd(), 'quests')
async function parseQuests() {
@@ -22,14 +29,17 @@ async function parseQuests() {
const content = markdown.slice(match[0].length)
const htmlContent = marked.parse(content)
const { title, order } = metadata
return {
name,
metadata,
title,
order,
content: htmlContent,
}
} catch (error) {
console.error(`Error parsing quest ${name}:`, error)
return null
throw error
}
})
)
@@ -37,4 +47,17 @@ async function parseQuests() {
return quests
}
parseQuests().then((quests) => console.log(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)
}