Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejs
themeEmacs
titleserver.js
const express = require('express');
const bodyParser = require('body-parser');

const HCX_API_URL = ''; // API URL - CLOVA Studio에서 url 확인 ex)https://clovastudio.apigw.ntruss.com/testapp/v1/chat-completions/HCX-003
const HCX_API_KEY = ''; // API KEY
const HCX_GATEWAY_KEY = '';// GATEWAY KEY

const app = express();
const router = express.Router();

router.post('/request', (request, response) => {
    const bodyData = request.body;

    requestHCX(response, bodyData)
        .then(() => response.end())
        .catch(err => {
        	console.error('[ERROR] requestHCX chat completion failed: ' + err);
            return resresponse.status(err.status || 500).json(err).end();
        });
});

/**
 * 하이퍼클로바 X 서버로 요청합니다.
 * @param {Response} response
 * @param {Object} body
 * @returns {Promise}
 */
function requestHCX(response, bodyData) {
    const source = axios.CancelToken.source();
    const url = HCX_API_URL;
	const headers= {
		'Content-Type': 'application/json',
        'Accept': 'text/event-stream',
		'X-NCP-CLOVASTUDIO-API-KEY': HCX_API_KEY,
        'X-NCP-APIGW-API-KEY': HCX_GATEWAY_KEY
	}
    return new Promise(async (resolve, reject) => {
        try {
            axios.post(url, bodyData, {
                headers,
                responseType: 'stream',
                cancelToken: source.token
            }).then(reshcxRes => {
                reshcxRes.data.pipe(resresponse);
            }).catch(reject);

            response.on('close', () => {
                source.cancel('요청을 취소합니다.');
                resolve();
            });
        } catch (e) {
            reject(e);
        }
    });
}

app.use(bodyParser.json());
app.use('/', router);
app.listen(8080);

...