@revas-hq/kit-endpoint
v0.0.3
Published
The `@revas-hq/kit-endpoint` package provides essential types and interfaces for defining and managing endpoints in your application. Inspired by Go-Kit endpoints, this package helps ensure consistent contracts and smooth integration with other libraries.
Downloads
18
Readme
Kit Endpoint Library
The @revas-hq/kit-endpoint
package provides essential types and interfaces for defining and managing endpoints in your application. Inspired by Go-Kit endpoints, this package helps ensure consistent contracts and smooth integration with other libraries.
Installation
Install the package using npm or yarn:
npm install @revas-hq/kit-endpoint
# or
yarn add @revas-hq/kit-endpoint
Types and Interfaces
EndpointMiddleware
A middleware function that wraps an endpoint, allowing you to modify its behavior.
type EndpointMiddleware = (next: Endpoint) => Endpoint;
Endpoint
The main function signature for an endpoint. It receives a Context and a request object, and returns a promise that resolves to an EndpointResult.
type Endpoint = (context: Context, request: any) => Promise<EndpointResult>;
EndpointResult
The result returned by an endpoint. It contains the context, an optional response, and an optional error.
type EndpointResult = {
context: Context;
response?: any;
error?: EndpointError;
};
EndpointError
Represents an error that can be returned by an endpoint.
type EndpointError = {
code: number;
message: string;
};
Usage
Defining an Endpoint
Endpoints are defined as asynchronous functions that take a Context and a request object, and return a promise with an EndpointResult.
import { Context, EndpointResult, Endpoint } from "@revas-hq/kit-endpoint";
const myEndpoint: Endpoint = async (
context: Context,
request: any,
): Promise<EndpointResult> => {
try {
// Business logic here
const response = { data: "some data" }; // Mock response
return {
context,
response,
};
} catch (error) {
return {
context,
error: {
code: 500,
message: "Internal Server Error",
},
};
}
};
Using Middleware
Middleware functions can wrap an endpoint to extend or modify its behavior.
import { Endpoint, EndpointMiddleware } from "@revas-hq/kit-endpoint";
const loggingMiddleware: EndpointMiddleware =
(next: Endpoint) => async (context: Context, request: any) => {
console.log("Request received:", request);
const result = await next(context, request);
console.log("Response:", result.response);
return result;
};
Combining Middleware and Endpoints
You can compose middleware functions to wrap an endpoint:
const endpointWithMiddleware = loggingMiddleware(myEndpoint);
endpointWithMiddleware(someContext, someRequest).then((result) => {
// Handle result
});
License
This project is licensed under the MIT License. See the LICENSE file for details.