Skip to content

Instantly share code, notes, and snippets.

@Eun
Last active June 14, 2024 17:21
Show Gist options
  • Save Eun/a1a3c14983ce4dfff65d6297ad2208b4 to your computer and use it in GitHub Desktop.
Save Eun/a1a3c14983ce4dfff65d6297ad2208b4 to your computer and use it in GitHub Desktop.
simple google apps script router that routes based on `path` url query
const router = Router();
router.Method("GET", "/", function(req, vars) {
return {"status": "ok"};
});
router.Method("GET", "/?<id>[A-Za-z0-9]+)", function(req, vars) {
return {"status": "ok", "id": vars.id};
});
router.Method("POST", "/", function(req, vars) {
return {"status": "ok"};
});
function doGet(req) {
return router.Serve("GET", req);
}
function doPost(req) {
return router.Serve("POST", req);
}
function Router() {
return {
Routes: [],
Respond: function(data) {
return ContentService
.createTextOutput(JSON.stringify(data))
.setMimeType(ContentService.MimeType.JSON);
},
Method: function(method, path, handler) {
this.Routes.push({
Method: method,
Path: path,
Regex: new RegExp('^'+path+'$'),
Handler: handler,
})
},
Serve: function(method, request) {
for (const route of this.Routes) {
if (route.Method != method) {
continue;
}
if (request.parameter == undefined || request.parameter.path == undefined) {
continue;
}
const re = new RegExp('^'+route.Path+'$');
const result = re.exec(request.parameter.path);
if (result != null) {
delete request.parameter.path;
return this.Respond(route.Handler(request, result.groups));
}
}
return this.Respond({
"status": 404,
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment