aboutsummaryrefslogtreecommitdiff
path: root/vnext/server/middleware/oembed.js
blob: ad23d9e208a35b0a9b4e5cf3087bc7220bd68b2d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { embeddedTweet } from '../../src/api';
import Cors from 'cors';

// Initializing the cors middleware
// You can read more about the available options here: https://github.com/expressjs/cors#configuration-options
const cors = Cors({
    methods: ['POST', 'GET', 'HEAD'],
});

/** 
 * Helper method to wait for a middleware to execute before continuing
 * And to throw an error when an error happens in a middleware
 * 
 * @param {import("next").NextApiRequest} req
 * @param {import("next").NextApiResponse} res
 * @param { Function } fn
 */
function runMiddleware(req, res, fn) {
    return new Promise((resolve, reject) => {
        fn(req, res, (result) => {
            if (result instanceof Error) {
                return reject(result);
            }
            return resolve(result);
        });
    });
}
/**
 * Return content for embedding.
 *
 * @param {import("next").NextApiRequest} req
 * @param {import("next").NextApiResponse} res
 */
const oembed = async (req, res) => {
    let url = (req.query.url || '').toString();
    await runMiddleware(req, res, cors);
    return embeddedTweet(url).then(result => {
        res.send(result);
        res.end();
    }).catch(err => {
        console.log(`Err: ${err.response.status}`);
        res.status(err.response.status);
        res.send({});
        res.end();
    });
};

export default oembed;