Strongly typed apis with autocompletion ans static type checking.
Fully typed list of remote methods with it's parameters and return values.
Automattic Validation and Serialization out of the box.
Local Validation (no need to make a server request to validate parameters)
Prefill request data to persist across multiple calls.
No compilation needed
Setting up the server
To be able to use the client the server must register a couple of routes required by the client to request remote methods metadata for validation and serialization. This routes are part of the @mionkit/commons package.
It is also required to export the type of the registered routes in the server.
// examples/server.routes.tsimport {RpcError} from'@mionkit/core';
import {Routes, registerRoutes} from'@mionkit/router';
import {clientRoutes} from'@mionkit/common';
import {Logger} from'Logger';
exporttypeUser = {id: string; name: string; surname: string};
exporttypeOrder = {id: string; date: Date; userId: string; totalUSD: number};
const routes = {
auth: {
headerName: 'authorization',
headerHook: (ctx, token: string): void => {
if (!token) thrownewRpcError({statusCode: 401, message: 'Not Authorized', name: ' Not Authorized'});
},
},
users: {
getById: (ctx, id: string): User => ({id, name: 'John', surname: 'Smith'}),
delete: (ctx, id: string): string => id,
create: (ctx, user: Omit<User, 'id'>): User => ({id: 'USER-123', ...user}),
},
orders: {
getById: (ctx, id: string): Order => ({id, date: newDate(), userId: 'USER-123', totalUSD: 120}),
delete: (ctx, id: string): string => id,
create: (ctx, order: Omit<Order, 'id'>): Order => ({id: 'ORDER-123', ...order}),
},
utils: {
sum: (ctx, a: number, b: number): number => a + b,
sayHello: (ctx, user: User): string =>`Hello ${user.name}${user.surname}`,
},
log: {
forceRunOnError: true,
hook: (ctx): any => {
Logger.log(ctx.path, ctx.request.headers, ctx.request.body);
},
},
} satisfies Routes;
// init server or serverless router// initHttpRouter(...);// initAwsLambdaRouter(...);// register routes and exporting the type of the Api to be used by clientconst myApi = registerRoutes(routes);
exporttypeMyApi = typeof myApi;
// register routes required by client, (these routes serve metadata, for validation and serialization)registerRoutes(clientRoutes);
Using the client
To use the client we just need to import the type of the registered routes, and initialize the client.
The methods object returned when initializing the client is a fully typed `RemoteApi`` object that contains all the remote methods with parameter types and return values.
// examples/client.tsimport {initClient} from'@mionkit/client';
// importing type only from serverimporttype {MyApi} from'./server.routes';
import {ParamsValidationResponse} from'@mionkit/reflection';
const port = 8076;
const baseURL = `http://localhost:${port}`;
const {methods, client} = initClient<MyApi>({baseURL});
// prefills the token for any future requests, value is stored in localStorageawait methods.auth('myToken-XYZ').prefill();
// calls sayHello route in the serverconst sayHello = await methods.utils.sayHello({id: '123', name: 'John', surname: 'Doe'}).call();
console.log(sayHello); // Hello John Doe// calls sumTwo route in the serverconst sumTwoResp = await methods.utils.sum(5, 2).call();
console.log(sumTwoResp); // 7// validate parameters locally without calling the serverconstvalidationResp: ParamsValidationResponse = await methods.utils
.sayHello({id: '123', name: 'John', surname: 'Doe'})
.validate();
console.log(validationResp); // {hasErrors: false, totalErrors: 0, errors: []}
Fully Typed Client
Handling Errors
When a remote route call fails, it always throws a RpcError this can be the error from the route or any other error thrown from the route's hooks.
All the methods operations: call, validate, prefill, removePrefill are async and throw a RpcError if something fails including validation and serialization.
As catch blocks are always of type any, the Type guard isRpcError can be used to check the correct type of the error.
// examples/handling-errors.tsimport {initClient} from'@mionkit/client';
// importing type only from serverimporttype {MyApi} from'./server.routes';
import {isRpcError, RpcError} from'@mionkit/core';
const port = 8076;
const baseURL = `http://localhost:${port}`;
const {methods, client} = initClient<MyApi>({baseURL});
try {
// calls sayHello route in the serverconst sayHello = await methods.utils.sayHello({id: '123', name: 'John', surname: 'Doe'}).call();
console.log(sayHello); // Hello John Doe
} catch (error: RpcError | any) {
// in this case the request has failed because the authorization hook is missingconsole.log(error); // {statusCode: 400, name: 'Validation Error', message: `Invalid params for Route or Hook 'auth'.`}if (isRpcError(error)) {
// ... handle the error as required
}
}
try {
// Validation throws an error when validation failsconst sayHello = await methods.utils.sayHello(nullasany).validate();
console.log(sayHello); // Hello John Doe
} catch (error: RpcError | any) {
console.log(error); // { statusCode: 400, name: 'Validation Error', message: `Invalid params ...`, errorData : {...}}
}
We found that @mionkit/client demonstrated a not healthy version release cadence and project activity because the last version was released a year ago.It has 1 open source maintainer collaborating on the project.
Package last updated on 15 Aug 2023
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.