Skip to content

Commit

Permalink
add origin passthrough to other endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
Razzmatazzz committed Sep 19, 2024
1 parent 8a78ee7 commit 178ce8d
Show file tree
Hide file tree
Showing 6 changed files with 104 additions and 67 deletions.
4 changes: 2 additions & 2 deletions graphql-yoga.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import graphqlUtil from './utils/graphql-util.mjs';
import graphQLOptions from './utils/graphql-options.mjs';

import useRequestTimer from './plugins/plugin-request-timer.mjs';
import useOriginServer from './plugins/plugin-origin-server.mjs';
import useGraphQLOrigin from './plugins/plugin-graphql-origin.mjs';
import useCacheMachine from './plugins/plugin-use-cache-machine.mjs';
import useTwitch from './plugins/plugin-twitch.mjs';
import useNightbot from './plugins/plugin-nightbot.mjs';
Expand Down Expand Up @@ -47,7 +47,7 @@ export default async function getYoga(env) {
useTwitch(env),
usePlayground(),
useCacheMachine(env),
useOriginServer(env),
useGraphQLOrigin(env),
useNightbot(env),
useLiteApi(env),
],
Expand Down
9 changes: 6 additions & 3 deletions index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,12 @@ async function graphqlHandler(request, env, ctx) {
// if an origin server is configured, pass the request
if (env.USE_ORIGIN === 'true') {
try {
const serverUrl = `https://api.tarkov.dev${graphQLOptions.baseEndpoint}`;
const queryResult = await fetchWithTimeout(serverUrl, {
method: request.method,
const originUrl = new URL(request.url);
if (env.ORIGIN_OVERRIDE) {
originUrl.host = env.ORIGIN_OVERRIDE;
}
const queryResult = await fetchWithTimeout(originUrl, {
method: 'POST',
body: JSON.stringify({
query,
variables,
Expand Down
34 changes: 34 additions & 0 deletions plugins/plugin-graphql-origin.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Pass the request to an origin server if USE_ORIGIN is set to 'true'
import fetchWithTimeout from '../utils/fetch-with-timeout.mjs';

export default function useGraphQLOrigin(env) {
return {
async onParams({params, request, setParams, setResult, fetchAPI}) {
if (env.USE_ORIGIN !== 'true') {
return;
}
try {
const originUrl = new URL(request.url);
if (env.ORIGIN_OVERRIDE) {
originUrl.host = env.ORIGIN_OVERRIDE;
}
const queryResult = await fetchWithTimeout(originUrl, {
method: request.method,
body: JSON.stringify(params),
headers: {
'Content-Type': 'application/json',
},
timeout: 20000
});
if (queryResult.status !== 200) {
throw new Error(`${queryResult.status} ${queryResult.statusText}: ${await queryResult.text()}`);
}
console.log('Request served from origin server');
setResult(await queryResult.json());
request.cached = true;
} catch (error) {
console.error(`Error getting response from origin server: ${error}`);
}
},
}
}
37 changes: 35 additions & 2 deletions plugins/plugin-lite-api.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import cacheMachine from '../utils/cache-machine.mjs';
import DataSource from '../datasources/index.mjs';
import graphqlUtil from '../utils/graphql-util.mjs';
import cacheMachine from '../utils/cache-machine.mjs';
import fetchWithTimeout from '../utils/fetch-with-timeout.mjs';

export const liteApiPathRegex = /\/api\/v1(?<gameMode>\/\w+)?\/(?<endpoint>item[\w\/]*)/;

Expand Down Expand Up @@ -45,7 +46,7 @@ export async function getLiteApiResponse(request, url, env, serverContext) {
const endpoint = pathInfo.groups.endpoint;

let key;
if (env.SKIP_CACHE !== 'true' && !request.headers.has('cache-check-complete')) {
if (env.SKIP_CACHE !== 'true' && env.SKIP_CACHE_CHECK !== 'true' && !request.headers.has('cache-check-complete')) {
const requestStart = new Date();
key = await cacheMachine.createKey(env, url.pathname, { q, lang, gameMode, uid, tags, sort, sort_direction });
const cachedResponse = await cacheMachine.get(env, {key});
Expand All @@ -64,6 +65,38 @@ export async function getLiteApiResponse(request, url, env, serverContext) {
} else {
//console.log(`Skipping cache in ${ENVIRONMENT} environment`);
}

if (env.USE_ORIGIN === 'true') {
try {
const originUrl = new URL(request.url);
if (env.ORIGIN_OVERRIDE) {
originUrl.host = env.ORIGIN_OVERRIDE;
}
const response = await fetchWithTimeout(originUrl, {
method: 'POST',
body: JSON.stringify({
q,
lang,
uid,
tags: tags?.join(','),
sort,
sort_direction,
}),
headers: {
'cache-check-complete': 'true',
},
timeout: 20000
});
if (response.status !== 200) {
throw new Error(`${response.status} ${await response.text()}`);
}
console.log('Request served from origin server');
return response;
} catch (error) {
console.error(`Error getting response from origin server: ${error}`);
}
}

const data = new DataSource(env);
const context = graphqlUtil.getDefaultContext(data);

Expand Down
29 changes: 27 additions & 2 deletions plugins/plugin-nightbot.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import cacheMachine from '../utils/cache-machine.mjs';
import DataSource from '../datasources/index.mjs';
import cacheMachine from '../utils/cache-machine.mjs';
import graphqlUtil from '../utils/graphql-util.mjs';
import fetchWithTimeout from '../utils/fetch-with-timeout.mjs';

function capitalize(s) {
return s && s[0].toUpperCase() + s.slice(1);
Expand Down Expand Up @@ -36,7 +37,7 @@ export async function getNightbotResponse(request, url, env, serverContext) {
const query = url.searchParams.get('q');

let key;
if (env.SKIP_CACHE !== 'true' && !request.headers.has('cache-check-complete')) {
if (env.SKIP_CACHE !== 'true' && env.SKIP_CACHE_CHECK !== 'true' && !request.headers.has('cache-check-complete')) {
const requestStart = new Date();
key = await cacheMachine.createKey(env, 'nightbot', { q: query, l: lang, m: gameMode });
const cachedResponse = await cacheMachine.get(env, {key});
Expand All @@ -55,6 +56,30 @@ export async function getNightbotResponse(request, url, env, serverContext) {
} else {
//console.log(`Skipping cache in ${ENVIRONMENT} environment`);
}

if (env.USE_ORIGIN === 'true') {
try {
const originUrl = new URL(request.url);
if (env.ORIGIN_OVERRIDE) {
originUrl.host = env.ORIGIN_OVERRIDE;
}
const response = await fetchWithTimeout(originUrl, {
method: 'GET',
headers: {
'cache-check-complete': 'true',
},
timeout: 20000
});
if (response.status !== 200) {
throw new Error(`${response.status} ${await response.text()}`);
}
console.log('Request served from origin server');
return response;
} catch (error) {
console.error(`Error getting response from origin server: ${error}`);
}
}

const data = new DataSource(env);
const context = graphqlUtil.getDefaultContext(data);

Expand Down
58 changes: 0 additions & 58 deletions plugins/plugin-origin-server.mjs

This file was deleted.

0 comments on commit 178ce8d

Please sign in to comment.