|
| 1 | +/* |
| 2 | + * Copyright 2020 Adobe. All rights reserved. |
| 3 | + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); |
| 4 | + * you may not use this file except in compliance with the License. You may obtain a copy |
| 5 | + * of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | + * |
| 7 | + * Unless required by applicable law or agreed to in writing, software distributed under |
| 8 | + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS |
| 9 | + * OF ANY KIND, either express or implied. See the License for the specific language |
| 10 | + * governing permissions and limitations under the License. |
| 11 | + */ |
| 12 | +/* eslint-disable camelcase */ |
| 13 | +const { fetch } = require('@adobe/helix-fetch'); |
| 14 | +const { utils } = require('@adobe/helix-shared'); |
| 15 | + |
| 16 | +async function extract(url, params, log = console) { |
| 17 | + const host = 'https://adobeioruntime.net'; |
| 18 | + const path = '/api/v1/web/helix/helix-services/run-query@v2/'; |
| 19 | + const query = url.split('/').pop(); |
| 20 | + const resource = `${host}${path}${query}`; |
| 21 | + const DEFAULT_CACHE = 'max-age=600'; |
| 22 | + |
| 23 | + const results = await fetch(url.startsWith(host) ? url : resource); |
| 24 | + const statusCode = utils.propagateStatusCode(results.status); |
| 25 | + const logLevel = utils.logLevelForStatusCode(results.status); |
| 26 | + const cacheControl = results.headers.get('cache-control'); |
| 27 | + |
| 28 | + try { |
| 29 | + if (!results.ok) { |
| 30 | + throw new Error(await results.text()); |
| 31 | + } |
| 32 | + return { |
| 33 | + statusCode, |
| 34 | + headers: { |
| 35 | + 'Content-Type': 'application/json', |
| 36 | + 'Cache-Control': cacheControl || DEFAULT_CACHE, |
| 37 | + }, |
| 38 | + body: (await results.json()).results, |
| 39 | + }; |
| 40 | + } catch (e) { |
| 41 | + log[logLevel](`data request to ${resource} failed ${e.message}`); |
| 42 | + return { |
| 43 | + statusCode, |
| 44 | + headers: { |
| 45 | + 'Content-Type': 'application/json', |
| 46 | + 'Cache-Control': 'max-age=60', |
| 47 | + }, |
| 48 | + body: [], |
| 49 | + }; |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +module.exports = { |
| 54 | + required: [], |
| 55 | + pattern: (url) => /(^https:\/\/adobeioruntime\.net\/api\/v1\/web\/helix\/helix-services\/run-query@.*)/.test(url) |
| 56 | + || /^\/?_query\/run-query\/.*$/.test(new URL(url).pathname), |
| 57 | + extract, |
| 58 | +}; |
0 commit comments