feat: refactor session management and API usage

- Add an import statement for the `get` function from `./utils/env.js`
- Add a constant for `API_ENDPOINT` using the `get` function
- Remove the `sessionId` constant declaration
- Add an `async` function `getSessionId` for fetching session ID
- Add an `async` function `main` for the main program logic
- Initialize `sessionId` using the command line argument or by calling `getSessionId`
- Add a console log statement for the session ID
- Remove the `if` statement for checking `sessionId` existence
- Update the socket URL to use `API_ENDPOINT`
- Add a `socket.on` event listener for the `close` event
- Update the condition for checking the `key` value in `stdin.on` event listener
- Call the `main` function at the end of the file

Signed-off-by: wancat <wancat@wancat.cc>
This commit is contained in:
wancat committed 2023-07-25 15:56:51 +08:00
1 parent 88ed447573
commit 9f74a80551
1 file changed
+47 -24
+47 -24
View File
@@ -1,37 +1,60 @@
/* eslint-disable no-underscore-dangle */
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 { get } from './utils/env.js'
const API_ENDPOINT = get('API_ENDPOINT', 'http://localhost:3000')
stdin.setRawMode(true) stdin.setRawMode(true)
stdin.resume() stdin.resume()
stdin.setEncoding('utf8') stdin.setEncoding('utf8')
const sessionId = process.argv[2] async function getSessionId() {
console.log(`Session ID: ${sessionId}`) const res = await fetch(`${API_ENDPOINT}/api/v1/sessions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
quest_id: 'helloworld',
}),
})
const data = await res.json()
return data._id
}
const socket = io('ws://localhost:3000', { async function main() {
query: { const sessionId = process.argv[2] || (await getSessionId())
session_id: sessionId, console.log(`Session ID: ${sessionId}`)
}, if (!sessionId) exit()
})
socket.on('open', function open() { const socket = io('ws://localhost:3000', {
console.log('Connected to the server.') query: {
}) session_id: sessionId,
},
})
socket.on('message', function incoming(data) { socket.on('open', function open() {
stdout.write(data) console.log('Connected to the server.')
}) })
socket.on('close', function close() { socket.on('message', function incoming(data) {
console.log('Disconnected from the server.') stdout.write(data)
exit() })
})
stdin.on('data', (key) => { socket.on('close', function close() {
if (key === '\u0003') { console.log('Disconnected from the server.')
socket.close()
exit() exit()
} else { })
socket.send(key)
} stdin.on('data', (key) => {
}) if (key === '\u0004') {
socket.close()
exit()
} else {
socket.send(key)
}
})
}
main()