Last active
September 12, 2022 06:51
-
-
Save daliborgogic/11c93fdee89e73472d499eab70695860 to your computer and use it in GitHub Desktop.
Gateway as a Service (GaaS)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createApi(baseUrl, defaults = {}) { | |
const callable = () => {} | |
callable.url = baseUrl | |
return new Proxy(callable, { | |
get({ url }, key) { | |
const method = key.toUpperCase() | |
if (['GET', 'POST', 'PUT', 'DELETE', 'PATCH'].includes(method)) { | |
return (data, overrides = {}) => { | |
const payload = { method, ...defaults, ...overrides } | |
switch (method) { | |
case 'GET': { | |
if (data) url = `${url}?${new URLSearchParams(data)}` | |
break | |
} | |
case 'POST': | |
case 'PUT': | |
case 'PATCH': { | |
payload.body = JSON.stringify(data) | |
} | |
} | |
return fetch(url, payload).then(d => d.json()) | |
} | |
} | |
return createApi(`${url}/${key}`, defaults) | |
} | |
}) | |
} | |
export { createApi } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"scripts": { | |
"dev": "wrangler dev --local --port 3000 --inspect false worker.mjs" | |
}, | |
"devDependencies": { | |
"wrangler": "^2.0.29" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createApi } from './api.mjs' | |
export default { | |
async fetch(request) { | |
try { | |
const headers = request.headers | |
const uri = new URL(request.url) | |
const { origin, pathname } = new URL(uri.pathname.substring(1)) | |
const api = createApi(origin, { headers }) | |
const payload = await api[pathname][request.method](uri.searchParams) | |
return Response.json(payload) | |
} catch (error) { | |
return Response.json({ error: error.message }) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment