Skip to content

Commit

Permalink
pass request query parameters to target host for proxy (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
rake7h authored Oct 28, 2023
1 parent ef3a820 commit ea4bae0
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 28 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,5 @@ yarn-error.log*
*.tsbuildinfo
next-env.d.ts
db/*
!db/README.md
!db/README.md
DEVNOTE.md
14 changes: 10 additions & 4 deletions src/helpers/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ interface MakeProxyRequest {
targetHost: AxiosRequestConfig['url'],
endpointPath: string,
data: AxiosRequestConfig['data']
params: Record<string, string>
}
interface MakeTargetURL {
reqPath:string
Expand All @@ -19,17 +20,18 @@ const makeTargetURL = ({ reqPath, targetURL }:MakeTargetURL) => {
/v2/get/users --> http://example.com/*
/v2/get/users --> http://example.com/v2/get/users
*/

let target = targetURL;

// if target url ends with /* append the reqPath

if (targetURL.endsWith('/*')) {
target = targetURL.replace('/*', path.normalize(reqPath))
}

return target;
}

const makeProxyRequest = async ({ headers, method, targetHost, endpointPath, data }: MakeProxyRequest) => {
const makeProxyRequest = async ({ headers, method, targetHost, endpointPath, data, params }: MakeProxyRequest) => {

/**
* basically, will call the proxy api with headers, query and
Expand Down Expand Up @@ -66,14 +68,18 @@ const makeProxyRequest = async ({ headers, method, targetHost, endpointPath, dat

const targetURL = makeTargetURL({ reqPath: endpointPath, targetURL: targetHost });

console.log('targetURL', targetURL)
console.log('targetURL', targetURL, params)
const config = {
method,
headers,
timeout: 20000,
url: targetURL,
data
params
}

// add data is present
if(data) config.data = data

console.log('axios', { config })
const axiosRes = await axios(config);
return axiosRes;
Expand Down
30 changes: 15 additions & 15 deletions src/helpers/utils/entrypoint.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {Endpoints} from '@/types'
import { readEndpointsFromDB } from '@/helpers/db/selectors';

interface getEndpointPathFromURL {
pathname: string,
url: string,
moxyPrefix?: string
}

Expand All @@ -14,25 +14,25 @@ if (queries.endpoint?.length) {
/**
* /moxy/v1/users/get --> /v1/users/get
*/
const getEndpointPathFromURL = ({ pathname, moxyPrefix = '/moxy' }: getEndpointPathFromURL) => {
if (!pathname) {
const getEndpointPathFromURL = ({ url, moxyPrefix = '/moxy' }: getEndpointPathFromURL):{
pathname:string, params: Record<string, string>
} => {
if (!url) {
throw ('url is missing for getEndpointPathFromURL()')
}

let formatedURL = pathname;
if (moxyPrefix && pathname.includes(moxyPrefix)) {
formatedURL = pathname.replace(moxyPrefix, '')
}
return formatedURL;
}
const { pathname, searchParams } = new URL(url.replace(moxyPrefix, ''), 'http://fake-base-host.com');
const params = Object.fromEntries(searchParams.entries())

return {pathname, params};
}

interface MatchEndpointPathToDB {
endpoint: string,
entrypointdDB: Array<Endpoints>
pathname: string,
}

const matchEndpointPathToDB = ({ endpoint, entrypointdDB }: MatchEndpointPathToDB) => {
return entrypointdDB.filter(ep=>ep.endpoint === endpoint)[0] || {};
const matchEndpointPathToDB = async ({ pathname }: MatchEndpointPathToDB) => {
const endpoints = await readEndpointsFromDB()
return endpoints.data.filter(ep => ep.endpoint === pathname)[0] || {};
}

export { getEndpointPathFromURL, matchEndpointPathToDB }
15 changes: 7 additions & 8 deletions src/pages/api/moxy/[...endpoint].ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
import type { NextApiRequest, NextApiResponse } from 'next'
import { readEndpointsFromDB, readCollectionByName } from '@/helpers/db/selectors';
import { readCollectionByName } from '@/helpers/db/selectors';
import { getEndpointPathFromURL, matchEndpointPathToDB } from '@/helpers/utils/entrypoint';
import { makeProxyRequest } from '@/helpers/proxy';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const queries = req.query;
const body = req.body;

// 1. get the endpoint from url, remove moxy
let pathname = getEndpointPathFromURL({ pathname: req.url || '' })
// 1. get the endpoint from url by removing /moxy prefix
const {pathname, params} = getEndpointPathFromURL({ url: req.url || '' })

// 2. math is this endpoint exist in db
const endpoints = await readEndpointsFromDB()
const { id, moxyType, proxyDetails, mockDetails } = matchEndpointPathToDB({ endpoint: pathname, entrypointdDB: endpoints.data })
// 2. get the endpoint details from db
const { id, moxyType, proxyDetails, mockDetails } = await matchEndpointPathToDB({ pathname: pathname })

if (!id) {
return res.status(500).json({ "message": `no mathing moxy entry found for ${pathname}` })
Expand All @@ -31,7 +29,8 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
method: req.method,
targetHost: proxyDetails.targetHost,
endpointPath: pathname,
data: JSON.stringify(body)
data: body ? JSON.stringify(body): undefined,
params
});

// Set the target response headers to the proxy response
Expand Down
29 changes: 29 additions & 0 deletions src/pages/api/test/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { NextApiRequest, NextApiResponse } from 'next'

const handler = async (req: NextApiRequest, res: NextApiResponse) => {

const queries = req.query;
const body = req.body;

/** Get test */
if (req.method === 'GET') {

if (queries.op === "1") {
return res.status(200).send('1');
}

if (queries.op === "2") {
return res.status(200).send('2');
}

return res.status(200).send('get');
}

/** POST test */
if (req.method === 'POST') {
return res.status(200).send(body);
}
}


export default handler;

0 comments on commit ea4bae0

Please sign in to comment.