Skip to content

Commit

Permalink
refactor: add meta in http
Browse files Browse the repository at this point in the history
  • Loading branch information
askuzminov committed Apr 7, 2021
1 parent aa743ae commit 8337749
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 22 deletions.
13 changes: 11 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ export const grpc = grpcHTTP({
timeout: undefined,

// Proxy xhr before request
transformRequest: ({ xhr }) => {
transformRequest: ({ xhr, data, meta }) => {
xhr.setRequestHeader('Authorization', 'ANY_TOKEN');
},

Expand All @@ -182,7 +182,7 @@ export const grpc = grpcHTTP({
},

// Proxy result after request
transformResponse: ({ data }) => {
transformResponse: ({ xhr, data, meta }) => {
if (!data.success) {
console.log(data.error);
}
Expand Down Expand Up @@ -357,6 +357,12 @@ await grpc(
#### All options
```ts
interface Meta {
token: string;
}

const grpc = grpcHTTP<Meta>(...);

const result = await grpc(
whisk_api_user_v2_UserAPI_UpdateSettings, // gRPC method
{ ... }, // gRPC params
Expand All @@ -366,6 +372,9 @@ const result = await grpc(
onDownload: e => console.log(e.loaded / e.total), // download progress with ProgressEvent
onUpload: e => console.log(e.loaded / e.total), // upload progress with ProgressEvent
timeout: 2000, // number - timeout for this request with cancel request at the end
meta: { // Meta - data for transformRequest and transformResponse methods
token: 'CODE',
},
}
);
```
Expand Down
12 changes: 6 additions & 6 deletions src/http/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const grpcCancel = (): Cancel => {
return CancelFn;
};

export const grpcHTTP = ({
export const grpcHTTP = <Meta = unknown>({
server,
transformRequest,
transformResponse,
Expand All @@ -27,7 +27,7 @@ export const grpcHTTP = ({
devtool = false,
debug = false,
logger,
}: ConfigGRPC) => {
}: ConfigGRPC<Meta>) => {
if (!isText(server)) {
throw new Error('No "server" in GRPC config');
}
Expand All @@ -37,7 +37,7 @@ export const grpcHTTP = ({
return (<T extends Field, K extends Field>(
field: Service<T, K>,
values = {} as ServiceRequest<Service<T, K>>,
{ cancel, onDownload, onUpload, mask, timeout }: LocalGRPC<T> = {}
{ cancel, onDownload, onUpload, mask, timeout, meta }: LocalGRPC<T, Meta> = {}
): Promise<GOutput<ServiceResponse<Service<T, K>>>> => {
if (isString(cancel) && isFunction(cancels[cancel])) {
cancels[cancel]();
Expand Down Expand Up @@ -181,7 +181,7 @@ export const grpcHTTP = ({

if (isFunction(transformRequest)) {
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
sendData = (await transformRequest({ xhr, data: values })) || values;
sendData = (await transformRequest({ xhr, data: values, meta })) || values;
}

const encoded = Encode(
Expand Down Expand Up @@ -219,11 +219,11 @@ export const grpcHTTP = ({

return data;
})
.then(data => (isFunction(transformResponse) ? transformResponse({ xhr, data }) : data))
.then(data => (isFunction(transformResponse) ? transformResponse({ xhr, data, meta }) : data))
.catch(data => {
logger?.error(method, data);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
return { success: false, error: { data } } as GError;
});
}) as GRPC;
}) as GRPC<Meta>;
};
25 changes: 15 additions & 10 deletions src/http/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export type GOutput<T> = GSuccess<T> | GError | GResult<T>;

type LoggerFn = (message?: any, ...optionalParams: any[]) => void;

export interface ConfigGRPC {
export interface ConfigGRPC<Meta = unknown> {
server: string;
credentials?: boolean;
timeout?: number;
Expand All @@ -52,16 +52,20 @@ export interface ConfigGRPC {
error: LoggerFn;
info: LoggerFn;
};
transformRequest?<T>(params: { xhr: XMLHttpRequest; data: T }): T | void | Promise<T | void>;
transformResponse?<T>(params: { xhr: XMLHttpRequest; data: GOutput<T> }): GOutput<T> | Promise<GOutput<T>>;
transformRequest?<T>(params: { xhr: XMLHttpRequest; data: T; meta?: Meta }): T | void | Promise<T | void>;
transformResponse?<T>(params: {
xhr: XMLHttpRequest;
data: GOutput<T>;
meta?: Meta;
}): GOutput<T> | Promise<GOutput<T>>;
}

export interface Cancel {
(): void;
abort?(): void;
}

export interface LocalGRPC<T extends Field> {
export interface LocalGRPC<T extends Field, Meta = unknown> {
mask?:
| boolean
| ('mask' extends keyof FieldGet<T>
Expand All @@ -77,18 +81,19 @@ export interface LocalGRPC<T extends Field> {
timeout?: number;
onDownload?: (e: ProgressEvent<EventTarget>) => void;
onUpload?: (e: ProgressEvent<EventTarget>) => void;
meta?: Meta;
}

export type GRPC = <T extends Field, K extends Field>(
export type GRPC<Meta = unknown> = <T extends Field, K extends Field>(
...[field, values, options]: {} extends ServiceRequest<Service<T, K>>
? [Service<T, K>, ServiceRequest<Service<T, K>>?, LocalGRPC<T>?]
: [Service<T, K>, ServiceRequest<Service<T, K>>, LocalGRPC<T>?]
? [Service<T, K>, ServiceRequest<Service<T, K>>?, LocalGRPC<T, Meta>?]
: [Service<T, K>, ServiceRequest<Service<T, K>>, LocalGRPC<T, Meta>?]
) => Promise<GOutput<ServiceResponse<Service<T, K>>>>;

export type GRPCDeep = <T extends Field, K extends Field>(
export type GRPCDeep<Meta = unknown> = <T extends Field, K extends Field>(
...[field, values, options]: {} extends ServiceRequestDeep<Service<T, K>>
? [Service<T, K>, ServiceRequestDeep<Service<T, K>>?, LocalGRPC<T>?]
: [Service<T, K>, ServiceRequestDeep<Service<T, K>>, LocalGRPC<T>?]
? [Service<T, K>, ServiceRequestDeep<Service<T, K>>?, LocalGRPC<T, Meta>?]
: [Service<T, K>, ServiceRequestDeep<Service<T, K>>, LocalGRPC<T, Meta>?]
) => Promise<GOutput<ServiceResponseDeep<Service<DeepReadonly<T>, DeepReadonly<K>>>>>;

// ...[method, params]: T[P]['request'] extends undefined ? [P] : [P, T[P]['request']]
Expand Down
19 changes: 15 additions & 4 deletions tests/demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,22 +36,30 @@ const forbidden = () => {
const TOKEN = '123';

(async () => {
interface Meta {
token: string;
}

// Server config
const grpc = grpcHTTP({
const grpc = grpcHTTP<Meta>({
server: 'https://example.com',
credentials: true,
debug: false,
devtool: false,
timeout: undefined,

// Proxy xhr before request
transformRequest: ({ xhr, data }) => {
transformRequest: ({ xhr, data, meta }) => {
xhr.setRequestHeader('Authorization', TOKEN);
console.log(meta?.token);
return { ...data, x: 1 };
},

// Proxy result after request
transformResponse: ({ data }) => {
transformResponse: ({ xhr, data, meta }) => {
console.log(xhr.status);
console.log(meta?.token);

if (!data.success) {
alert(`v1.Grpc.Event.GRPCError ${data.error.message ?? ''}`);

Expand All @@ -67,7 +75,7 @@ const TOKEN = '123';
}
return data;
},
}) as GRPCDeep;
}) as GRPCDeep<Meta>; // Deep example

// Simple method call
const user = await grpc(whisk_api_user_v2_UserAPI_GetMe);
Expand Down Expand Up @@ -121,6 +129,9 @@ const TOKEN = '123';
onDownload: e => console.log(e.loaded / e.total),
onUpload: e => console.log(e.loaded / e.total),
timeout: 2000,
meta: {
token: '12',
},
}
);

Expand Down

0 comments on commit 8337749

Please sign in to comment.