From 9f74a805517811c1573e6b5a3a2a640cb9941121 Mon Sep 17 00:00:00 2001 From: wancat Date: Tue, 25 Jul 2023 15:56:51 +0800 Subject: [PATCH] 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 --- server/src/client.js | 71 +++++++++++++++++++++++++++++--------------- 1 file changed, 47 insertions(+), 24 deletions(-) diff --git a/server/src/client.js b/server/src/client.js index 40e16cd..e4bd7f2 100644 --- a/server/src/client.js +++ b/server/src/client.js @@ -1,37 +1,60 @@ +/* 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] -console.log(`Session ID: ${sessionId}`) +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 +} -const socket = io('ws://localhost:3000', { - query: { - session_id: sessionId, - }, -}) +async function main() { + const sessionId = process.argv[2] || (await getSessionId()) + console.log(`Session ID: ${sessionId}`) + if (!sessionId) exit() -socket.on('open', function open() { - console.log('Connected to the server.') -}) + const socket = io('ws://localhost:3000', { + query: { + session_id: sessionId, + }, + }) -socket.on('message', function incoming(data) { - stdout.write(data) -}) + socket.on('open', function open() { + console.log('Connected to the server.') + }) -socket.on('close', function close() { - console.log('Disconnected from the server.') - exit() -}) + socket.on('message', function incoming(data) { + stdout.write(data) + }) -stdin.on('data', (key) => { - if (key === '\u0003') { - socket.close() + socket.on('close', function close() { + console.log('Disconnected from the server.') exit() - } else { - socket.send(key) - } -}) + }) + + stdin.on('data', (key) => { + if (key === '\u0004') { + socket.close() + exit() + } else { + socket.send(key) + } + }) +} + +main()