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 axios = require('axios');
const bodyParser = require('body-parser');

const DALLE_URL = ''; // API URL ex) 'https://api.openai.com/v1/images/generations'
const DALLE_API_KEY = ''; // API KEY

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

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

    requestDALLEServer(response, bodyData)
        .then(() => response.end())
        .catch((error) => response.status(error.status).json(error).end());
});

/**
 * DALL·E 서버로 요청을 합니다.
 * @param {ObjectResponse} body 전송할 Data Objectresponse
 * @param {ResponseObject} resbodyData 클라이언트 응답
객체  * @returns {Promise}
 */
function requestDALLEServer(resresponse, bodybodyData) {
    const source = axios.CancelToken.source();
    const url = DALLE_URL;

    return new Promise((resolve, reject) => {
        try {
            axios.post(url, body, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${DALLE_API_KEY}`
                },
                responseType: 'stream',
                cancelToken: source.token
            }).then(response => {
                response.data.pipe(resresponse);
            }).catch(error => {
                reject({
                    status: error.response ? error.response.status : 500,
                    message: error.message
                });
            });

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


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

...