New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@mionkit/client

Package Overview
Dependencies
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@mionkit/client - npm Package Compare versions

Comparing version 0.6.2 to 0.7.0

6

.dist/cjs/src/client.js

@@ -14,3 +14,7 @@ "use strict";

const rootProxy = new MethodProxy([], client, clientOptions);
return { client, methods: rootProxy.proxy };
return {
client,
routes: rootProxy.proxy,
hooks: rootProxy.proxy,
};
}

@@ -17,0 +21,0 @@ exports.initClient = initClient;

@@ -11,3 +11,7 @@ import { DEFAULT_PREFILL_OPTIONS } from './constants';

const rootProxy = new MethodProxy([], client, clientOptions);
return { client, methods: rootProxy.proxy };
return {
client,
routes: rootProxy.proxy,
hooks: rootProxy.proxy,
};
}

@@ -14,0 +18,0 @@ class MionClient {

5

.dist/types/src/client.d.ts

@@ -1,2 +0,2 @@

import { ClientMethods, ClientOptions, HookSubRequest, InitOptions, RouteSubRequest, SubRequest, SuccessClientResponse } from './types';
import { ClientOptions, HookSubRequest, InitOptions, RouteSubRequest, SubRequest, SuccessClientResponse, ClientRoutes, ClientHooks } from './types';
import type { RemoteApi } from '@mionkit/router';

@@ -6,3 +6,4 @@ import { ParamsValidationResponse } from '@mionkit/reflection';

client: MionClient;
methods: ClientMethods<RM>;
routes: ClientRoutes<RM>;
hooks: ClientHooks<RM>;
};

@@ -9,0 +10,0 @@ declare class MionClient {

@@ -1,2 +0,2 @@

import type { ResolvedPublicResponses } from '@mionkit/router';
import type { RemoteMethodResponses } from '@mionkit/router';
import { RequestErrors, ValidationRequest } from './types';

@@ -7,3 +7,3 @@ export declare function validateSubRequests(subRequestIds: string[], req: ValidationRequest, errors: RequestErrors, validateRouteHooks?: boolean): void;

export declare function serializeSubRequest(id: string, req: ValidationRequest, errors: RequestErrors): void;
export declare function deserializeResponseBody(responseBody: ResolvedPublicResponses, req: ValidationRequest): ResolvedPublicResponses;
export declare function deserializeResponseBody(responseBody: RemoteMethodResponses, req: ValidationRequest): RemoteMethodResponses;
//# sourceMappingURL=reflection.d.ts.map

@@ -1,2 +0,2 @@

import type { ResolvedPublicResponses } from '@mionkit/router';
import type { RemoteMethodResponses } from '@mionkit/router';
import { ClientOptions, HookSubRequest, SubRequest, ReflectionById, MetadataById, RouteSubRequest } from './types';

@@ -16,5 +16,5 @@ import { ParamsValidationResponse } from '@mionkit/reflection';

response: Response | undefined;
rawResponseBody: ResolvedPublicResponses | undefined;
rawResponseBody: RemoteMethodResponses | undefined;
constructor(options: ClientOptions, metadataById: MetadataById, reflectionById: ReflectionById, route?: RR | undefined, hooks?: HookRequestsList | undefined);
call(): Promise<ResolvedPublicResponses>;
call(): Promise<RemoteMethodResponses>;
validateParams(subReqList?: SubRequest<any>[]): Promise<ParamsValidationResponse[]>;

@@ -21,0 +21,0 @@ prefill(subReqList?: SubRequest<any>[]): Promise<void>;

@@ -69,5 +69,15 @@ import { RpcError } from '@mionkit/core';

export type RouteCall<RR extends RemoteRouteMetadata> = (...params: Parameters<RR['_handler']>) => RouteSubRequest<RR>;
export type ClientMethods<RMS extends RemoteApi<any>> = {
[Property in keyof RMS]: RMS[Property] extends RemoteRouteMetadata ? RouteCall<RMS[Property]> : RMS[Property] extends RemoteHookMetadata | RemoteHeaderHookMetadata ? HookCall<RMS[Property]> : RMS[Property] extends RemoteApi<any> ? ClientMethods<RMS[Property]> : never;
export type NonClientRoute = never | RemoteHookMetadata | RemoteHeaderHookMetadata;
export type ClientRoutes<RMS extends RemoteApi<any>> = {
[Property in keyof RMS as RMS[Property] extends NonClientRoute ? never : Property]: RMS[Property] extends RemoteRouteMetadata ? RouteCall<RMS[Property]> : RMS[Property] extends RemoteApi<any> ? ClientRoutes<RMS[Property]> : never;
};
export type NonClientHook = never | RemoteRouteMetadata | {
[key: string]: RemoteRouteMetadata;
};
export type ClientHooks<RMS extends RemoteApi<any>> = {
[Property in keyof RMS as RMS[Property] extends NonClientHook ? never : Property]: RMS[Property] extends RemoteHookMetadata | RemoteHeaderHookMetadata ? HookCall<RMS[Property]> : RMS[Property] extends RemoteApi<any> ? ClientHooks<RMS[Property]> : never;
};
export type Cleaned<RMS extends RemoteApi<any>> = {
[Property in keyof RMS as RMS[Property] extends never ? never : Property]: RMS[Property];
};
export type SuccessClientResponse<RR extends RouteSubRequest<any>, RHList extends HookSubRequest<any>[]> = [

@@ -100,5 +110,9 @@ SuccessResponse<RR>,

export declare type __ΩRouteCall = any[];
export declare type __ΩClientMethods = any[];
export declare type __ΩNonClientRoute = any[];
export declare type __ΩClientRoutes = any[];
export declare type __ΩNonClientHook = any[];
export declare type __ΩClientHooks = any[];
export declare type __ΩCleaned = any[];
export declare type __ΩSuccessClientResponse = any[];
export declare type __ΩValidationRequest = any[];
//# sourceMappingURL=types.d.ts.map
{
"name": "@mionkit/client",
"version": "0.6.2",
"version": "0.7.0",
"description": "Browser client for mion Apps.",

@@ -60,9 +60,9 @@ "keywords": [

"@deepkit/type": "^1.0.1-alpha.97",
"@mionkit/core": "^0.6.0",
"@mionkit/reflection": "^0.6.0"
"@mionkit/core": "^0.7.0",
"@mionkit/reflection": "^0.7.0"
},
"gitHead": "19ecae7b2b13659181b9c055c6f6c8da2e8942da",
"gitHead": "e815480a3509f885cd438801b8fd830178f626c7",
"devDependencies": {
"@mionkit/http": "^0.6.2",
"@mionkit/router": "^0.6.2",
"@mionkit/http": "^0.7.0",
"@mionkit/router": "^0.7.0",
"dom-storage": "^2.1.0",

@@ -69,0 +69,0 @@ "jest-environment-jsdom": "^29.6.2"

@@ -9,3 +9,3 @@ <p align="center">

<p align="center">
<strong>Fully typed client for mion Apis
<strong>Fully typed client for mion APIs
</strong>

@@ -20,3 +20,3 @@ </p>

Modern client for mion Apis:
Modern client for mion APIs:

@@ -30,143 +30,8 @@ - Strongly typed apis with autocompletion ans static type checking.

## Setting up the server
## Check Out The [Website And Documentation](http://mion.io) 📚
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.
[![mion-website-banner](https://raw.githubusercontent.com/MionKit/mion/master/assets/public/mion-website-banner.png)](http://mion.io)
It is also required to export the **type** of the registered routes in the server.
---
```ts
// examples/server.routes.ts
import {RpcError} from '@mionkit/core';
import {Routes, registerRoutes} from '@mionkit/router';
import {clientRoutes} from '@mionkit/common';
import {Logger} from 'Logger';
export type User = {id: string; name: string; surname: string};
export type Order = {id: string; date: Date; userId: string; totalUSD: number};
const routes = {
auth: {
headerName: 'authorization',
headerHook: (ctx, token: string): void => {
if (!token) throw new RpcError({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: new Date(), 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 client
const myApi = registerRoutes(routes);
export type MyApi = 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.
```ts
// examples/client.ts
import {initClient} from '@mionkit/client';
// importing type only from server
import type {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 localStorage
await methods.auth('myToken-XYZ').prefill();
// calls sayHello route in the server
const sayHello = await methods.utils.sayHello({id: '123', name: 'John', surname: 'Doe'}).call();
console.log(sayHello); // Hello John Doe
// calls sumTwo route in the server
const sumTwoResp = await methods.utils.sum(5, 2).call();
console.log(sumTwoResp); // 7
// validate parameters locally without calling the server
const validationResp: ParamsValidationResponse = await methods.utils
.sayHello({id: '123', name: 'John', surname: 'Doe'})
.validate();
console.log(validationResp); // {hasErrors: false, totalErrors: 0, errors: []}
```
#### Fully Typed Client
![autocomplete](https://raw.githubusercontent.com/MionKit/mion/master/assets/public/autocomplete.gif)
## 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.
```ts
// examples/handling-errors.ts
import {initClient} from '@mionkit/client';
// importing type only from server
import type {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 server
const 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 missing
console.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 fails
const sayHello = await methods.utils.sayHello(null as any).validate();
console.log(sayHello); // Hello John Doe
} catch (error: RpcError | any) {
console.log(error); // { statusCode: 400, name: 'Validation Error', message: `Invalid params ...`, errorData : {...}}
}
```
_[MIT](../../LICENSE) LICENSE_

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc