From 4e1739cd1607730b6dd2c090c98c945cb69ba8c1 Mon Sep 17 00:00:00 2001 From: Emi Matchu Date: Thu, 1 Feb 2024 08:36:21 -0800 Subject: [PATCH] Add CORS headers to /api/assetImage Sometimes main DTI gets this back as the image URL for a movie asset, we need to be able to request it! --- pages/api/assetImage.js | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/pages/api/assetImage.js b/pages/api/assetImage.js index ffb7705..8b1c377 100644 --- a/pages/api/assetImage.js +++ b/pages/api/assetImage.js @@ -24,6 +24,8 @@ const beeline = require("honeycomb-beeline")({ const puppeteer = require("puppeteer"); const genericPool = require("generic-pool"); +const { applyCORSHeaders } = require("../../src/server/cors"); + console.info(`Creating new browser instance`); const browserPromise = puppeteer.launch({ headless: true }); @@ -48,12 +50,20 @@ const PAGE_POOL = genericPool.createPool( }, validate: (page) => page.browser().isConnected(), }, - { min: 4, max: 4, testOnBorrow: true, acquireTimeoutMillis: 15000 } + { min: 4, max: 4, testOnBorrow: true, acquireTimeoutMillis: 15000 }, ); PAGE_POOL.on("factoryCreateError", (error) => console.error(error)); PAGE_POOL.on("factoryDestroyError", (error) => console.error(error)); async function handle(req, res) { + // Apply CORS headers, to allow Classic DTI to request this. + // If this is an OPTIONS request asking for CORS info, return an empty + // response with just the CORS headers applied. + applyCORSHeaders(req, res); + if (req.method === "OPTIONS") { + return res.status(204).end(); + } + const { libraryUrl, size } = req.query; if (!libraryUrl) { return reject(res, "libraryUrl is required"); @@ -62,7 +72,7 @@ async function handle(req, res) { if (!isNeopetsUrl(libraryUrl)) { return reject( res, - `libraryUrl must be an HTTPS Neopets URL, but was: ${libraryUrl}` + `libraryUrl must be an HTTPS Neopets URL, but was: ${libraryUrl}`, ); } @@ -97,7 +107,7 @@ async function loadAndScreenshotImage(libraryUrl, size) { // NOTE: If we deploy to a host where localhost:3000 won't work, make this // configurable with an env var, e.g. process.env.LOCAL_APP_HOST const assetImagePageUrl = new URL( - "http://localhost:3000/internal/assetImage" + "http://localhost:3000/internal/assetImage", ); assetImagePageUrl.search = new URLSearchParams({ libraryUrl, @@ -139,7 +149,7 @@ async function loadAndScreenshotImage(libraryUrl, size) { } else { throw new Error( `Assertion error: Promise.any did not return an errorMessage or an imageBuffer: ` + - `${JSON.stringify(Object.keys(firstResultFromPage))}` + `${JSON.stringify(Object.keys(firstResultFromPage))}`, ); } } finally { @@ -206,7 +216,7 @@ Promise.any = async function handleWithBeeline(req, res) { beeline.withTrace( { name: "api/assetImage", operation_name: "api/assetImage" }, - () => handle(req, res) + () => handle(req, res), ); }