astro-assert
- Proper Assertions for Astro Endpoints
astro-assert
provides an easy and effective way to assert conditions within your Astro API routes, ensuring that your endpoints handle errors gracefully and return the correct HTTP responses. This package streamlines error handling and validation, allowing you to focus on building your Astro project with confidence.
npm install astro-assert
bun install astro-assert
pnpm install astro-assert
yarn add astro-assert
export const GET: APIRoute = ({ params, request }) => {
return new Response(JSON.stringify({
message: "This was a GET!"
})
)
}
import { AssertAPIRoute, astroApiAssert } from 'astro-assert';
export const GET: APIRoute = async ({ request, params }) => AssertAPIRoute(async () => {
let aCoolParam = params.a_cool_param;
// Default Response("Something went wrong", 400)
astroApiAssert(aCoolParam);
// Or provide a custom error message and status code
astroApiAssert(aCoolParam, "aCoolParam not found", 404);
return new Response(JSON.stringify({
message: "This was a GET!"
});
});
Wrap your API route logic within this function to ensure that assertions are checked before proceeding. If any assertion fails, an appropriate response is automatically returned.
Asserts that the given value is truthy. If not, it throws a response with the provided message and status code.
value
(any
): The value to assert.message
(string
): The error message to return if the assertion fails (default: "Something went wrong").statusCode
(number
): The HTTP status code to return if the assertion fails (default: 400).
- Simplified Error Handling: Easily manage assertions and error responses in your Astro API routes.
- Customizable Responses: Control the error message and status code, making it adaptable to various use cases.
- Streamlined Code: Keep your API logic clean and focused by reducing boilerplate error handling code.
Feel free to open issues and pull requests to help improve the package. Contributions are always welcome!
MIT License. See the LICENSE file for more information.