feat: add initial task on session creation

This commit is contained in:
wancat committed 2023-09-01 17:16:32 +08:00
1 parent 97b0fb0f1d
commit 0ea44e1f71
7 files changed
+58 -27

No files matched your search

+1
View File
@@ -9,6 +9,7 @@ lerna-debug.log*
.bash_history .bash_history
.viminfo .viminfo
*.swp *.swp
home
# Diagnostic reports (https://nodejs.org/api/report.html) # Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
+19 -13
View File
@@ -1,8 +1,11 @@
/* eslint-disable no-underscore-dangle */ /* eslint-disable no-underscore-dangle */
import axios from 'axios'
import { stdin, stdout, exit } from 'process' import { stdin, stdout, exit } from 'process'
import { io } from 'socket.io-client' import { io } from 'socket.io-client'
import { program } from 'commander' import { program } from 'commander'
let api = null
function get(key, defaultValue) { function get(key, defaultValue) {
const value = process.env[key] const value = process.env[key]
if (value != null) { if (value != null) {
@@ -20,26 +23,23 @@ function debug(...args) {
} }
} }
async function createdSession() { async function createSession() {
console.log('Creating a new session...') console.log('Creating a new session...')
const res = await fetch(`${program.opts().host}/api/v1/sessions`, { const res = await api.post('/sessions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
quest_id: 'helloworld', quest_id: 'helloworld',
}),
}) })
const data = await res.json() const { data } = await res
if (!data._id) {
console.error(data)
exit(1)
}
console.log('Created Session ID:', data._id) console.log('Created Session ID:', data._id)
return data return data
} }
async function getSessionList() { async function getSessionList() {
const res = await fetch(`${program.opts().host}/api/v1/sessions`) const res = await api.get('/sessions')
const data = await res.json() return res.data
return data
} }
async function lastSession() { async function lastSession() {
@@ -102,12 +102,18 @@ async function connect(sessionId) {
} }
async function main() { async function main() {
api = axios.create({
baseURL: `${program.opts().host}/api/v1`,
headers: {
'Content-Type': 'application/json',
},
})
console.log(program.opts().session) console.log(program.opts().session)
// main() // main()
const sessionId = const sessionId =
program.opts().session || program.opts().session ||
(program.opts().create ? (await createdSession())._id : null) || (program.opts().create ? (await createSession())._id : null) ||
(await lastSession())._id (await lastSession())._id
await connect(sessionId) await connect(sessionId)
+1
View File
@@ -8,6 +8,7 @@
"start": "node index.js" "start": "node index.js"
}, },
"dependencies": { "dependencies": {
"axios": "^1.5.0",
"commander": "^11.0.0", "commander": "^11.0.0",
"socket.io-client": "^4.7.2" "socket.io-client": "^4.7.2"
} }
@@ -1,6 +1,7 @@
import Session from '../../models/session.js' import Session from '../../models/session.js'
import Quest from '../../models/quest.js' import Quest from '../../models/quest.js'
import { createContainer } from '../../containers/docker.js' import { createContainer } from '../../containers/docker.js'
import SessionHandler from '../../game/sessionHandler.js'
export async function getSessionList(req, res) { export async function getSessionList(req, res) {
try { try {
@@ -45,20 +46,22 @@ export async function createSession(req, res) {
} }
try { try {
const progress = quest.stages[0].id
const container = await createContainer( const container = await createContainer(
`quest-${quest.id}-${req.user.username}-${Date.now()}` `quest-${quest.id}-${req.user.username}-${Date.now()}`
) )
const newSession = new Session({ const newSession = new Session({
user: req.user, user: req.user,
quest, quest,
progress,
containerId: container.id, containerId: container.id,
}) })
const session = await newSession.save() const session = new SessionHandler(newSession)
res.status(201).json(session) session.addNewTasks()
await newSession.save()
res.status(201).json(newSession)
} catch (err) { } catch (err) {
console.error(err)
res.status(400).json({ message: err.message }) res.status(400).json({ message: err.message })
} }
} }
-1
View File
@@ -75,7 +75,6 @@ export default class CommandHandler extends SessionHandler {
.filter((s) => this.isMatch(s)) .filter((s) => this.isMatch(s))
.reduce((r, s) => ({ ...r, ...this.execute(s) }), {}) .reduce((r, s) => ({ ...r, ...this.execute(s) }), {})
console.log(this.session)
return { return {
end: this.session.status === 'finished', end: this.session.status === 'finished',
...response, ...response,
+21 -9
View File
@@ -1,8 +1,9 @@
import { pushToSession } from '../api/socket.js' import { pushToSession } from '../api/socket.js'
export default class SessionWrapper { export default class SessionHandler {
constructor(session) { constructor(session) {
this.session = session this.session = session
this.quest = session.quest
} }
getTask(stage) { getTask(stage) {
@@ -22,29 +23,40 @@ export default class SessionWrapper {
) )
} }
getNewTasks() {
const stages = this.getStages()
return stages
.filter((s) => s.task)
.filter((s) => !this.session.tasks.some((t) => t.id === s.id))
.map((s) => ({ id: s.id, name: s.task, completed: false }))
}
addNewTasks() {
const newTasks = this.getNewTasks()
this.session.tasks.push(...newTasks)
pushToSession(this.session.id, 'tasks', this.session.tasks)
}
execute(stage) { execute(stage) {
this.session.tasks this.session.tasks
.filter((t) => t.id === stage.id) .filter((t) => t.id === stage.id)
.forEach((t) => { .forEach((t) => {
t.completed = true t.completed = true
}) })
this.session.hints.push(...stage.hints) this.session.hints.push(...stage.hints)
pushToSession(this.session.id, 'hints', stage.hints)
if (stage.id === 'END') { if (stage.id === 'END') {
this.session.status = 'finished' this.session.status = 'finished'
this.session.finishedAt = new Date() this.session.finishedAt = new Date()
} }
const stages = this.getStages()
console.debug(stages)
const newTasks = stages
.filter((s) => s.task)
.map((s) => ({ id: s.id, name: s.task, completed: false }))
this.session.tasks.push(...newTasks) this.addNewTasks()
pushToSession(this.session.id, 'tasks', this.session.tasks)
return { return {
responses: stage.responses, responses: stage.responses,
hints: stage.hints, hints: stage.hints,
tasks: newTasks,
} }
} }
} }
+9
View File
@@ -1207,6 +1207,15 @@ axios@^1.4.0:
form-data "^4.0.0" form-data "^4.0.0"
proxy-from-env "^1.1.0" proxy-from-env "^1.1.0"
axios@^1.5.0:
version "1.5.0"
resolved "https://registry.yarnpkg.com/axios/-/axios-1.5.0.tgz#f02e4af823e2e46a9768cfc74691fdd0517ea267"
integrity sha512-D4DdjDo5CY50Qms0qGQTTw6Q44jl7zRwY7bthds06pUGfChBCTcQs+N743eFWGEd6pRTMd6A+I87aWyFV5wiZQ==
dependencies:
follow-redirects "^1.15.0"
form-data "^4.0.0"
proxy-from-env "^1.1.0"
babel-jest@^29.6.1: babel-jest@^29.6.1:
version "29.6.1" version "29.6.1"
resolved "https://registry.yarnpkg.com/babel-jest/-/babel-jest-29.6.1.tgz#a7141ad1ed5ec50238f3cd36127636823111233a" resolved "https://registry.yarnpkg.com/babel-jest/-/babel-jest-29.6.1.tgz#a7141ad1ed5ec50238f3cd36127636823111233a"