Last active
June 14, 2024 17:21
-
-
Save Eun/a1a3c14983ce4dfff65d6297ad2208b4 to your computer and use it in GitHub Desktop.
simple google apps script router that routes based on `path` url query
This file contains 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
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); | |
} |
This file contains 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 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