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
+25 -2
+25 -2
View File
@@ -1,12 +1,32 @@
/* eslint-disable no-underscore-dangle */
import { stdin, stdout, exit } from 'process'
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.resume()
stdin.setEncoding('utf8')
const sessionId = process.argv[2]
async function getSessionId() {
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
}
async function main() {
const sessionId = process.argv[2] || (await getSessionId())
console.log(`Session ID: ${sessionId}`)
if (!sessionId) exit()
const socket = io('ws://localhost:3000', {
query: {
@@ -28,10 +48,13 @@ socket.on('close', function close() {
})
stdin.on('data', (key) => {
if (key === '\u0003') {
if (key === '\u0004') {
socket.close()
exit()
} else {
socket.send(key)
}
})
}
main()