update documentation

This commit is contained in:
Philipp Kunz 2024-04-14 18:58:55 +02:00
parent 23c03fd623
commit 5e5f4003e0
4 changed files with 155 additions and 99 deletions

View File

@ -2,17 +2,33 @@
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"githost": "code.foss.global",
"gitscope": "api.global",
"gitrepo": "typedrequest",
"description": "make typed requests towards apis",
"description": "A TypeScript library for making typed requests towards APIs, including facilities for handling requests, routing, and virtual stream handling.",
"npmPackagename": "@api.global/typedrequest",
"license": "MIT",
"projectDomain": "api.global"
"projectDomain": "api.global",
"keywords": [
"TypeScript",
"API Requests",
"HTTP",
"Typed Programming",
"Request Routing",
"Response Handling",
"Virtual Streams",
"Asynchronous",
"Network Communication",
"Server Communication",
"API Integration"
]
}
},
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
},
"tsdoc": {
"legal": "\n## License and Legal Information\n\nThis 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. \n\n**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.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
}
}

View File

@ -2,7 +2,7 @@
"name": "@api.global/typedrequest",
"version": "3.0.19",
"private": false,
"description": "make typed requests towards apis",
"description": "A TypeScript library for making typed requests towards APIs, including facilities for handling requests, routing, and virtual stream handling.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"type": "module",
@ -47,5 +47,18 @@
],
"browserslist": [
"last 1 chrome versions"
],
"keywords": [
"TypeScript",
"API Requests",
"HTTP",
"Typed Programming",
"Request Routing",
"Response Handling",
"Virtual Streams",
"Asynchronous",
"Network Communication",
"Server Communication",
"API Integration"
]
}
}

1
readme.hints.md Normal file
View File

@ -0,0 +1 @@

214
readme.md
View File

@ -1,109 +1,135 @@
# @apiglobal/typedrequest
make typed requests towards apis
# @api.global/typedrequest
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@apiglobal/typedrequest)
* [gitlab.com (source)](https://gitlab.com/apiglobal/typedrequest)
* [github.com (source mirror)](https://github.com/apiglobal/typedrequest)
* [docs (typedoc)](https://apiglobal.gitlab.io/typedrequest/)
A TypeScript library for making typed requests towards APIs, providing interfaces and classes to handle request/response cycles using typed definitions. It supports building and handling requests, routing based on request types, and virtual stream handling over networks.
## Status for master
## Install
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/apiglobal/typedrequest/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/apiglobal/typedrequest/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@apiglobal/typedrequest)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/apiglobal/typedrequest)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@apiglobal/typedrequest)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@apiglobal/typedrequest)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@apiglobal/typedrequest)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
To install `@api.global/typedrequest`, you can use npm or yarn. Run the following command in your project directory:
```
npm install @api.global/typedrequest --save
```
Or, if you prefer yarn:
```
yarn add @api.global/typedrequest
```
This package is designed to facilitate making typed requests to APIs, ensuring that both requests and responses adhere to predefined interfaces. This enhances the predictability and reliability of network communication in applications that interact with APIs.
## Usage
Use TypeScript for best in class intellisense.
Utilizing `@api.global/typedrequest` involves several core concepts, including the creation of typed requests, handling virtual streams, defining request handlers, and routing requests based on their type. Below are comprehensive examples and explanations of how to use these features in your applications.
### Setting Up a Typed Request
The foundation of `@api.global/typedrequest` is the `TypedRequest` class, which allows you to define requests that are strictly typed. This ensures that both the request sent and the response received match the expected structures.
First, define an interface that represents your request and response data structure:
```typescript
import { expect, tap } from '@pushrocks/tapbundle';
import * as smartexpress from '@pushrocks/smartexpress';
import * as typedrequest from '../ts/index';
let testServer: smartexpress.Server;
let testTypedHandler: typedrequest.TypedHandler<ITestReqRes>;
// lets define an interface
interface ITestReqRes {
method: 'hi';
request: {
name: string;
};
response: {
surname: string;
};
// Define an interface for your request/response structure
interface IUserRequest {
method: 'getUser';
request: { userId: string };
response: { username: string; email: string; };
}
tap.test('should create a typedHandler', async () => {
// lets use the interface in a TypedHandler
testTypedHandler = new typedrequest.TypedHandler<ITestReqRes>('hi', async (reqArg) => {
return {
surname: 'wow',
};
});
});
tap.test('should spawn a server to test with', async () => {
testServer = new smartexpress.Server({
cors: true,
forceSsl: false,
port: 3000,
});
});
tap.test('should define a testHandler', async () => {
const testTypedRouter = new typedrequest.TypedRouter(); // typed routers can broker typedrequests between handlers
testTypedRouter.addTypedHandler(testTypedHandler);
testServer.addRoute(
'/testroute',
new smartexpress.HandlerTypedRouter(testTypedRouter as any) // the "any" is testspecific, since smartexpress ships with its own version of typedrequest.
);
});
tap.test('should start the server', async () => {
await testServer.start();
});
tap.test('should fire a request', async () => {
const typedRequest = new typedrequest.TypedRequest<ITestReqRes>(
'http://localhost:3000/testroute',
'hi'
);
const response = await typedRequest.fire({
name: 'really',
});
console.log('this is the response:');
console.log(response);
expect(response.surname).to.equal('wow');
});
tap.test('should end the server', async () => {
await testServer.stop();
});
tap.start();
```
## Contribution
Next, create an instance of `TypedRequest` using this interface, and use it to make an API call:
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
```typescript
import { TypedRequest } from '@api.global/typedrequest';
For further information read the linked docs at the top of this readme.
// Construct a TypedRequest instance for fetching user data
const getUserRequest = new TypedRequest<IUserRequest>('https://your-api.com/users', 'getUser');
> MIT licensed | **&copy;** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
// Execute the request with a specific userId and log the response
const userResponse = await getUserRequest.fire({ userId: 'user-123' });
console.log(userResponse.username);
```
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)
### Handling Virtual Streams
`@api.global/typedrequest` introduces the concept of virtual streams, allowing you to manage real-time data transfer over the network as streams. You can create a virtual stream, send data, and read data from it as shown below:
```typescript
import { VirtualStream } from '@api.global/typedrequest';
// Instantiate a VirtualStream for handling real-time data
const myStream = new VirtualStream<ArrayBufferLike>();
// Use the stream to send data
await myStream.sendData(new TextEncoder().encode("Hello, World!"));
// Retrieve data from the stream
const receivedData = await myStream.fetchData();
console.log(new TextDecoder().decode(receivedData));
```
### Defining and Using Handlers
To process requests, you can define handlers that are responsible for specific types of requests:
```typescript
import { TypedHandler } from '@api.global/typedrequest';
interface IAdditionRequest {
method: 'add';
request: { a: number; b: number; };
response: { result: number; };
}
// Create a handler for processing addition requests
const additionHandler = new TypedHandler<IAdditionRequest>('add', async (req) => {
return { result: req.a + req.b };
});
```
### Routing Requests
`TypedRouter` is used to route requests to their appropriate handlers based on the request type:
```typescript
import { TypedRouter } from '@api.global/typedrequest';
const router = new TypedRouter();
// Associate the additionHandler with the router
router.addTypedHandler(additionHandler);
// The router now directs 'add' requests to the additionHandler
```
### Error Handling
`@api.global/typedrequest` provides a `TypedResponseError` class to facilitate error handling in typed requests:
```typescript
import { TypedResponseError } from '@api.global/typedrequest';
// Throw a TypedResponseError with details about the error
throw new TypedResponseError('An error occurred', { detail: 'Error details' });
```
This comprehensive overview covers the essential features provided by `@api.global/typedrequest`. By adhering to defined request and response structures, you can create more reliable and maintainable applications that interact seamlessly with APIs.
## 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.
**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.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.