Created
May 31, 2022 03:02
-
-
Save cjfswd/45197407cc3377b0088b23ce7ecb9fd5 to your computer and use it in GitHub Desktop.
nuxt 3 parse http endpoint dynamically
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
export default defineEventHandler((event) => { | |
let { req, res } = event; | |
const params = String(event.context.params._).split('/').filter(item => item != '') | |
if (params.length == 0) { | |
switch (req.method) { | |
case "GET": | |
res.statusCode = 200 | |
return 'All resources getted with success.'; | |
case "POST": | |
res.statusCode = 201 | |
return 'Resource created with success.'; | |
default: | |
res.statusCode = 405 | |
res.setHeader('Allow', ['GET', 'POST']) | |
return `${event.req.method} Method not allowed.` | |
} | |
} | |
if (params.length == 1) { | |
const id = Number(params[0]); | |
switch (req.method) { | |
case "GET": | |
res.statusCode = 200 | |
return 'Resource getted with success.'; | |
case "PUT": | |
res.statusCode = 200 | |
return `Resource { Id: ${id} } updated with success.`; | |
case "DELETE": | |
res.statusCode = 200 | |
return `Resource { Id: ${id} } deleted with success.`; | |
default: | |
res.statusCode = 405 | |
res.setHeader('Allow', ['GET', 'PUT', 'DELETE']) | |
return `${event.req.method} Method not allowed.` | |
} | |
} | |
if (params.length > 1) { | |
res.statusCode = 400 | |
return 'Bad Request.'; | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment