feat(ci): Set up GitHub Actions workflows for CI/CD

This commit is contained in:
2024-12-25 14:23:42 +01:00
parent 32577ade65
commit 7c4140800b
22 changed files with 10050 additions and 26129 deletions

173
readme.md
View File

@@ -1,15 +1,16 @@
# @push.rocks/smartstatus
status information in TypeScript
A TypeScript library for managing HTTP status information, with detailed status classes.
## Install
To install `@push.rocks/smartstatus`, you can use npm (or yarn, or pnpm) by running the following command in your terminal:
To install `@push.rocks/smartstatus`, use npm (or yarn, or pnpm) by running the following command in your terminal:
```sh
npm install @push.rocks/smartstatus --save
```
Ensure you have TypeScript and a package to work with TypeScript in your project. If not, you might want to add TypeScript and ts-node (for a start) to your project:
Ensure you have TypeScript and a package to work with TypeScript in your project. If not, you might want to install TypeScript and ts-node (for development purposes) to your project:
```sh
npm install typescript ts-node --save-dev
@@ -17,36 +18,48 @@ npm install typescript ts-node --save-dev
## Usage
Using `@push.rocks/smartstatus` allows you to handle HTTP status codes more effectively in TypeScript. Below are examples detailing how to utilize this module in various scenarios.
The `@push.rocks/smartstatus` library provides a structured and comprehensive way to handle HTTP status codes in TypeScript, enhancing your ability to manage HTTP responses effectively. Below, we outline an extensive set of scenarios demonstrating how you can leverage this module's capabilities to streamline and enrich your response handling from server-side applications to API endpoints.
### Getting Started
Ensure you import the module into your TypeScript file:
To start using `@push.rocks/smartstatus`, ensure you import the module into your TypeScript files. Here's a basic import statement you can use:
```typescript
import * as smartstatus from '@push.rocks/smartstatus';
```
For more specific imports, such as obtaining particular HTTP status code classes, you may use:
```typescript
import { HttpStatus, Status404, Status200 } from '@push.rocks/smartstatus';
```
### Retrieving a Specific Status
You can retrieve specific HTTP status information by using its respective class or a convenient method for fetching it by the status code string.
The library allows you to retrieve any HTTP status code with its corresponding information quickly. You can do this by using either a class representation for known statuses or using a method that fetches the status by its status code string.
#### Example: Fetching 404 Not Found Status
Let's say you wish to work with the HTTP 404 "Not Found" status. You can retrieve its details as follows:
```typescript
import { HttpStatus } from '@push.rocks/smartstatus';
const notFoundStatus = smartstatus.HttpStatus.getHttpStatusByString('404');
const notFoundStatus = HttpStatus.getHttpStatusByString('404');
console.log(notFoundStatus.code); // 404
console.log(notFoundStatus.text); // Not Found
console.log(notFoundStatus.description); // The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.
```
This method `getHttpStatusByString` dynamically returns an instance of the respective status class filled with relevant data such as the HTTP code, text, and a descriptive message.
The `getHttpStatusByString` function dynamically returns an instance of the respective status class with fields like HTTP code, textual representation, and an insightful description of the status.
### Handling Errors with HTTP Statuses
### Handling Errors Using HTTP Statuses
When building a web application or an API, handling different HTTP statuses becomes crucial. Here's an example of how you could use `smartstatus` to enrich error handling in your Express.js app:
One of the most valuable features of `@push.rocks/smartstatus` is enriching error handling protocols in web applications or APIs. Let's illustrate how smartstatus can be used with an Express.js framework to enhance HTTP response management, specifically handling different HTTP error statuses.
#### Example: Implementing with Express.js
Imagine you are developing a web service, and a specific operation fails due to an authorization issue. Here's how you might use smartstatus to handle this error gracefully:
```typescript
import express from 'express';
@@ -54,52 +67,142 @@ import { HttpStatus } from '@push.rocks/smartstatus';
const app = express();
app.get('/some/endpoint', (req, res) => {
// Some logic that might fail
if (someConditionNotMet) {
const unauthorizedStatus = HttpStatus.getHttpStatusByString('401');
res.status(unauthorizedStatus.code).json({
error: unauthorizedStatus.text,
message: unauthorizedStatus.description,
});
}
app.get('/secure/data', (req, res) => {
// Simulating an authorization failure condition
const userIsAuthorized = false;
if (!userIsAuthorized) {
const unauthorizedStatus = HttpStatus.getHttpStatusByString('401');
res.status(unauthorizedStatus.code).json({
error: unauthorizedStatus.text,
message: unauthorizedStatus.description,
});
} else {
res.status(200).send('Secure Data');
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
```
In the above scenario, if a specific condition is not met (implying some authorization failure), we respond with a 401 Unauthorized status, along with a message detailing the issue.
In this express app endpoint, if the user is not authorized to access the resource, it responds with a 401 Unauthorized status. This status code is enriched with a detailed message derived from smartstatus, providing a helpful explanation to API consumers.
### Extending with Custom Statuses
While `@push.rocks/smartstatus` provides a structured manner to handle known HTTP statuses, there might be scenarios where you need custom statuses for internal signaling or specialized clients.
While `@push.rocks/smartstatus` covers standard HTTP statuses, the library also allows you to define and manage custom status codes tailored to specific application needs. This is particularly useful for internal APIs requiring bespoke statuses.
Extending or adding new statuses is straightforward:
#### Example: Creating a Custom HTTP Status
Let's say you want to create a unique status for indicating a special condition encountered by your application, such as a "Processing Error" that is represented by code 499. Define a custom status class as follows:
```typescript
import { HttpStatus } from '@push.rocks/smartstatus';
class Status418 extends HttpStatus {
constructor() {
super({ code: 418, text: 'I'm a teapot', description: 'The requested entity body is short and stout. Tip me over and pour me out.' });
}
class Status499 extends HttpStatus {
constructor() {
super({
code: 499,
text: 'Processing Error',
description:
'The server encountered a processing error which prevented it from completing the request.',
});
}
}
// Register the custom status
HttpStatus.addStatus('418', Status418);
// Register the custom status for use
HttpStatus.addStatus('499', Status499);
// Retrieve and use the custom status
const customStatus = HttpStatus.getHttpStatusByString('418');
console.log(`${customStatus.code} ${customStatus.text}`); // 418 I'm a teapot
// Usage of the custom status
const processingErrorStatus = HttpStatus.getHttpStatusByString('499');
console.log(`${processingErrorStatus.code} ${processingErrorStatus.text}`); // 499 Processing Error
```
This approach ensures that your application can manage both standard and custom status codes effectively, maintaining a clear and expressive way to handle HTTP responses.
This custom status can then be used in the same way as predefined statuses in the library, allowing you to handle unique responses efficiently.
### Conclusion
### Comprehensive Examples Across HTTP Status Ranges
By integrating `@push.rocks/smartstatus` into your TypeScript applications, you gain a powerful tool to manage HTTP status codes, improving the readability and maintainability of your code when dealing with HTTP responses. Whether you are building web applications, APIs, or services, `smartstatus` offers a structured approach to handling success and error states across your application.
The `smartstatus` library classifies statuses across different ranges (1xx, 2xx, 3xx, 4xx, and 5xx). Here, we will demonstrate how to handle each of these categories to provide robustness in response management.
#### Informational Responses (1xx)
Status codes in the 1xx range inform the client about the progress of the request. These are mostly used in scenarios involving continuation or switching protocols.
```typescript
import { Status100 } from '@push.rocks/smartstatus';
// Handling 100 Continue status
const continueStatus = new Status100();
console.log(continueStatus.code, continueStatus.text, continueStatus.description);
```
#### Successful Responses (2xx)
The 2xx successes indicate that the client's request was received, understood, and accepted. Utilizing these codes effectively can aid in confirming successful API operations.
```typescript
import { Status200, Status201 } from '@push.rocks/smartstatus';
// 200 OK status for successfully processed requests
const okStatus = new Status200();
console.log(okStatus.code, okStatus.text, okStatus.description);
// 201 Created status for resource creation
const createdStatus = new Status201();
console.log(createdStatus.code, createdStatus.text, createdStatus.description);
```
#### Redirection Messages (3xx)
Statuses in the 3xx range indicate redirection, offering guidance on how the client can access different resources or follow up with another request.
```typescript
import { Status301, Status302 } from '@push.rocks/smartstatus';
// Permanent and Temporary redirects
const movedPermanentlyStatus = new Status301();
console.log(movedPermanentlyStatus.text); // Moved Permanently
const foundStatus = new Status302();
console.log(foundStatus.text); // Found
```
#### Client Error Responses (4xx)
This class of status codes is intended to inform the client that the error seems to have been caused by the client, such as a malformed request.
```typescript
import { Status400, Status404 } from '@push.rocks/smartstatus';
// Using 400 Bad Request for malformed requests
const badRequestStatus = new Status400();
console.log(badRequestStatus.description);
// Handling 404 Not Found for missing resources
const notFoundStatus = new Status404();
console.log(notFoundStatus.description);
```
#### Server Error Responses (5xx)
5xx indicates server-side errors, signaling the server is aware it encountered an error or is otherwise incapable of performing the request.
```typescript
import { Status500, Status503 } from '@push.rocks/smartstatus';
// Internal server error handling
const internalServerErrorStatus = new Status500();
console.log(internalServerErrorStatus.text);
// Service unavailable handling with a 503 response
const serviceUnavailableStatus = new Status503();
console.log(serviceUnavailableStatus.description);
```
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.