diff options
author | Vitaly Takmazov | 2022-10-29 23:35:20 +0300 |
---|---|---|
committer | Vitaly Takmazov | 2023-01-13 10:37:58 +0300 |
commit | 47218df561e877265c739ffab59b760318ea3143 (patch) | |
tree | 166dd029133aca8d0d60af50535bb579bd6b8096 /vnext/server/middleware/oembed.js | |
parent | 3a403e4023ce3b7074a7922e7b504263ddc7a3d1 (diff) |
Merge server routes from Next version
Diffstat (limited to 'vnext/server/middleware/oembed.js')
-rw-r--r-- | vnext/server/middleware/oembed.js | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/vnext/server/middleware/oembed.js b/vnext/server/middleware/oembed.js new file mode 100644 index 00000000..ad23d9e2 --- /dev/null +++ b/vnext/server/middleware/oembed.js @@ -0,0 +1,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; |