...
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
const express = require('express'); const axios = require('axios'); const bodyParser = require('body-parser'); const GEMINI_URL = ''; // API URL ex) 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:streamGenerateContent' const GEMINI_PARAM = ''; // API PARAMETER ex) '?alt=sse&key=' const GEMINI_KEY = ''; // API KEY const app = express(); const router = express.Router(); router.post('/request', (request, response) => { const bodyData = Object.assign({}, request.body); requestGeminiServer(response, bodyData) .then(() => response.end()) .catch((err) => response.status(err.status || 500).json(err).end()); }); /** * Gemini 서버로 요청을 합니다. * @param {Response} response * @param {Object} bodyData * @returns {Promise} */ function requestGeminiServer(response, bodyData) { const url = GEMINI_URL; const key = GEMINI_KEY; const param = GEMINI_PARAM; const urlWithParam = `${url}?${param}key=${key}`; const source = axios.CancelToken.source(); return new Promise((resolve, reject) => { try { axios.post(urlWithParam, bodyData, { headers: { 'Content-Type': 'application/json' }, responseType: 'stream', cancelToken: source.token }).then(geminiRes => { geminiRes.data.pipe(response); }).catch(reject); response.on('close', () => { source.cancel('요청을 취소합니다.'); resolve(); }); } catch (e) { reject(e); } }); } app.use(bodyParser.json()); app.use('/', router); app.listen(8080); |
...