Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(client): support headers in client #2611

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 121 additions & 7 deletions packages/libs/chainweb-node-client/etc/chainweb-node-client.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ export type ChainwebChainId = (typeof CHAINS)[number];
// @alpha
export type ChainwebNetworkId = 'mainnet01' | 'testnet04' | 'testnet05' | 'development';

// @alpha (undocumented)
export type ClientRequestInit = Omit<RequestInit, 'method' | 'body'>;

// @alpha (undocumented)
export function convertIUnsignedTransactionToNoSig(transaction: IUnsignedCommand): ICommand;

Expand Down Expand Up @@ -86,7 +89,7 @@ export interface ILocalCommandResult {
}

// @alpha (undocumented)
export interface ILocalOptions {
export interface ILocalOptions extends ClientRequestInit {
// (undocumented)
preflight?: boolean;
// (undocumented)
Expand Down Expand Up @@ -153,7 +156,7 @@ export interface ISPVRequestBody {
}

// @alpha
export function listen(requestBody: IListenRequestBody, apiHost: string): Promise<ICommandResult>;
export function listen(requestBody: IListenRequestBody, apiHost: string, requestInit?: ClientRequestInit): Promise<ICommandResult>;

// @alpha (undocumented)
export type ListenResponse = ICommandResult;
Expand All @@ -162,7 +165,7 @@ export type ListenResponse = ICommandResult;
export function local<T extends ILocalOptions>(requestBody: LocalRequestBody, apiHost: string, options?: T): Promise<LocalResponse<T>>;

// @alpha
export function localRaw(requestBody: LocalRequestBody, apiHost: string, { preflight, signatureVerification, }: {
export function localRaw(requestBody: LocalRequestBody, apiHost: string, { preflight, signatureVerification, ...requestInit }: ILocalOptions & {
signatureVerification: boolean;
preflight: boolean;
}): Promise<IPreflightResult | ICommandResult>;
Expand Down Expand Up @@ -191,22 +194,133 @@ export function parseResponse<T>(response: Response): Promise<T>;
export function parseResponseTEXT(response: Response): Promise<string>;

// @alpha
export function poll(requestBody: IPollRequestBody, apiHost: string, confirmationDepth?: number): Promise<IPollResponse>;
export function poll(requestBody: IPollRequestBody, apiHost: string, confirmationDepth?: number, requestInit?: ClientRequestInit): Promise<IPollResponse>;

// @alpha
export function send(requestBody: ISendRequestBody, apiHost: string): Promise<SendResponse>;
export function send(requestBody: ISendRequestBody, apiHost: string, requestInit?: ClientRequestInit): Promise<SendResponse>;

// @alpha
export type SendResponse = IRequestKeys;

// @alpha
export function spv(requestBody: ISPVRequestBody, apiHost: string): Promise<SPVResponse | Response>;
export function spv(requestBody: ISPVRequestBody, apiHost: string, requestInit?: ClientRequestInit): Promise<SPVResponse | Response>;

// @alpha
export type SPVResponse = SPVProof;

// @alpha
export function stringifyAndMakePOSTRequest<T>(body: T): object;
export function stringifyAndMakePOSTRequest<T>(body: T, requestInit?: ClientRequestInit): {
headers: {
'Content-Type': string;
} | {
length: number;
toString(): string;
toLocaleString(): string;
pop(): [string, string] | undefined;
push(...items: [string, string][]): number;
concat(...items: ConcatArray<[string, string]>[]): [string, string][];
concat(...items: ([string, string] | ConcatArray<[string, string]>)[]): [string, string][];
join(separator?: string | undefined): string;
reverse(): [string, string][];
shift(): [string, string] | undefined;
slice(start?: number | undefined, end?: number | undefined): [string, string][];
sort(compareFn?: ((a: [string, string], b: [string, string]) => number) | undefined): [string, string][];
splice(start: number, deleteCount?: number | undefined): [string, string][];
splice(start: number, deleteCount: number, ...items: [string, string][]): [string, string][];
unshift(...items: [string, string][]): number;
indexOf(searchElement: [string, string], fromIndex?: number | undefined): number;
lastIndexOf(searchElement: [string, string], fromIndex?: number | undefined): number;
every<S extends [string, string]>(predicate: (value: [string, string], index: number, array: [string, string][]) => value is S, thisArg?: any): this is S[];
every(predicate: (value: [string, string], index: number, array: [string, string][]) => unknown, thisArg?: any): boolean;
some(predicate: (value: [string, string], index: number, array: [string, string][]) => unknown, thisArg?: any): boolean;
forEach(callbackfn: (value: [string, string], index: number, array: [string, string][]) => void, thisArg?: any): void;
map<U>(callbackfn: (value: [string, string], index: number, array: [string, string][]) => U, thisArg?: any): U[];
filter<S_1 extends [string, string]>(predicate: (value: [string, string], index: number, array: [string, string][]) => value is S_1, thisArg?: any): S_1[];
filter(predicate: (value: [string, string], index: number, array: [string, string][]) => unknown, thisArg?: any): [string, string][];
reduce(callbackfn: (previousValue: [string, string], currentValue: [string, string], currentIndex: number, array: [string, string][]) => [string, string]): [string, string];
reduce(callbackfn: (previousValue: [string, string], currentValue: [string, string], currentIndex: number, array: [string, string][]) => [string, string], initialValue: [string, string]): [string, string];
reduce<U_1>(callbackfn: (previousValue: U_1, currentValue: [string, string], currentIndex: number, array: [string, string][]) => U_1, initialValue: U_1): U_1;
reduceRight(callbackfn: (previousValue: [string, string], currentValue: [string, string], currentIndex: number, array: [string, string][]) => [string, string]): [string, string];
reduceRight(callbackfn: (previousValue: [string, string], currentValue: [string, string], currentIndex: number, array: [string, string][]) => [string, string], initialValue: [string, string]): [string, string];
reduceRight<U_2>(callbackfn: (previousValue: U_2, currentValue: [string, string], currentIndex: number, array: [string, string][]) => U_2, initialValue: U_2): U_2;
find<S_2 extends [string, string]>(predicate: (value: [string, string], index: number, obj: [string, string][]) => value is S_2, thisArg?: any): S_2 | undefined;
find(predicate: (value: [string, string], index: number, obj: [string, string][]) => unknown, thisArg?: any): [string, string] | undefined;
findIndex(predicate: (value: [string, string], index: number, obj: [string, string][]) => unknown, thisArg?: any): number;
fill(value: [string, string], start?: number | undefined, end?: number | undefined): [string, string][];
copyWithin(target: number, start: number, end?: number | undefined): [string, string][];
entries(): IterableIterator<[number, [string, string]]>;
keys(): IterableIterator<number>;
values(): IterableIterator<[string, string]>;
includes(searchElement: [string, string], fromIndex?: number | undefined): boolean;
flatMap<U_3, This = undefined>(callback: (this: This, value: [string, string], index: number, array: [string, string][]) => U_3 | readonly U_3[], thisArg?: This | undefined): U_3[];
flat<A, D extends number = 1>(this: A, depth?: D | undefined): FlatArray<A, D>[];
[Symbol.iterator](): IterableIterator<[string, string]>;
[Symbol.unscopables]: {
[x: number]: boolean | undefined;
length?: boolean | undefined;
toString?: boolean | undefined;
toLocaleString?: boolean | undefined;
pop?: boolean | undefined;
push?: boolean | undefined;
concat?: boolean | undefined;
join?: boolean | undefined;
reverse?: boolean | undefined;
shift?: boolean | undefined;
slice?: boolean | undefined;
sort?: boolean | undefined;
splice?: boolean | undefined;
unshift?: boolean | undefined;
indexOf?: boolean | undefined;
lastIndexOf?: boolean | undefined;
every?: boolean | undefined;
some?: boolean | undefined;
forEach?: boolean | undefined;
map?: boolean | undefined;
filter?: boolean | undefined;
reduce?: boolean | undefined;
reduceRight?: boolean | undefined;
find?: boolean | undefined;
findIndex?: boolean | undefined;
fill?: boolean | undefined;
copyWithin?: boolean | undefined;
entries?: boolean | undefined;
keys?: boolean | undefined;
values?: boolean | undefined;
includes?: boolean | undefined;
flatMap?: boolean | undefined;
flat?: boolean | undefined;
[Symbol.iterator]?: boolean | undefined;
readonly [Symbol.unscopables]?: boolean | undefined;
at?: boolean | undefined;
};
at(index: number): [string, string] | undefined;
'Content-Type': string;
} | {
'Content-Type': string;
} | {
append(name: string, value: string): void;
delete(name: string): void;
get(name: string): string | null;
getSetCookie(): string[];
has(name: string): boolean;
set(name: string, value: string): void;
forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: any): void;
'Content-Type': string;
};
method: string;
body: string;
cache?: RequestCache | undefined;
credentials?: RequestCredentials | undefined;
integrity?: string | undefined;
keepalive?: boolean | undefined;
mode?: RequestMode | undefined;
priority?: RequestPriority | undefined;
redirect?: RequestRedirect | undefined;
referrer?: string | undefined;
referrerPolicy?: ReferrerPolicy | undefined;
signal?: AbortSignal | null | undefined;
window?: null | undefined;
};

// (No @packageDocumentation comment for this package)

Expand Down
4 changes: 3 additions & 1 deletion packages/libs/chainweb-node-client/src/listen.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { ICommandResult, IListenRequestBody } from './interfaces/PactAPI';
import type { ClientRequestInit } from './local';
import { parseResponse } from './parseResponse';
import { stringifyAndMakePOSTRequest } from './stringifyAndMakePOSTRequest';
import { fetch } from './utils/fetch';
Expand All @@ -13,8 +14,9 @@ import { fetch } from './utils/fetch';
export async function listen(
requestBody: IListenRequestBody,
apiHost: string,
requestInit?: ClientRequestInit,
): Promise<ICommandResult> {
const request = stringifyAndMakePOSTRequest(requestBody);
const request = stringifyAndMakePOSTRequest(requestBody, requestInit);
const listenUrl = new URL(`${apiHost}/api/v1/listen`);

const response = await fetch(listenUrl.toString(), request);
Expand Down
22 changes: 18 additions & 4 deletions packages/libs/chainweb-node-client/src/local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,12 @@ import { fetch } from './utils/fetch';
/**
* @alpha
*/
export interface ILocalOptions {
export type ClientRequestInit = Omit<RequestInit, 'method' | 'body'>;

/**
* @alpha
*/
export interface ILocalOptions extends ClientRequestInit {
preflight?: boolean;
signatureVerification?: boolean;
}
Expand Down Expand Up @@ -41,7 +46,11 @@ export async function local<T extends ILocalOptions>(
apiHost: string,
options?: T,
): Promise<LocalResponse<T>> {
const { signatureVerification = true, preflight = true } = options ?? {};
const {
signatureVerification = true,
preflight = true,
...requestInit
} = options ?? {};

if (!signatureVerification) {
requestBody = convertIUnsignedTransactionToNoSig(requestBody);
Expand All @@ -51,6 +60,7 @@ export async function local<T extends ILocalOptions>(
const result = await localRaw(body, apiHost, {
preflight,
signatureVerification,
...requestInit,
});

return parsePreflight(result);
Expand All @@ -72,9 +82,13 @@ export async function localRaw(
{
preflight,
signatureVerification,
}: { signatureVerification: boolean; preflight: boolean },
...requestInit
}: ILocalOptions & {
signatureVerification: boolean;
preflight: boolean;
},
): Promise<IPreflightResult | ICommandResult> {
const request = stringifyAndMakePOSTRequest(requestBody);
const request = stringifyAndMakePOSTRequest(requestBody, requestInit);
const localUrlWithQueries = new URL(`${apiHost}/api/v1/local`);

localUrlWithQueries.searchParams.append('preflight', preflight.toString());
Expand Down
4 changes: 3 additions & 1 deletion packages/libs/chainweb-node-client/src/poll.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { IPollRequestBody, IPollResponse } from './interfaces/PactAPI';
import type { ClientRequestInit } from './local';
import { parseResponse } from './parseResponse';
import { stringifyAndMakePOSTRequest } from './stringifyAndMakePOSTRequest';
import { fetch } from './utils/fetch';
Expand All @@ -18,8 +19,9 @@ export async function poll(
requestBody: IPollRequestBody,
apiHost: string,
confirmationDepth = 0,
requestInit?: ClientRequestInit,
): Promise<IPollResponse> {
const request = stringifyAndMakePOSTRequest(requestBody);
const request = stringifyAndMakePOSTRequest(requestBody, requestInit);
const pollUrl = new URL(`${apiHost}/api/v1/poll`);
if (confirmationDepth > 0) {
pollUrl.searchParams.append(
Expand Down
4 changes: 3 additions & 1 deletion packages/libs/chainweb-node-client/src/send.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { ISendRequestBody, SendResponse } from './interfaces/PactAPI';
import type { ClientRequestInit } from './local';
import { parseResponse } from './parseResponse';
import { stringifyAndMakePOSTRequest } from './stringifyAndMakePOSTRequest';
import { fetch } from './utils/fetch';
Expand All @@ -16,8 +17,9 @@ import { fetch } from './utils/fetch';
export async function send(
requestBody: ISendRequestBody,
apiHost: string,
requestInit?: ClientRequestInit,
): Promise<SendResponse> {
const request = stringifyAndMakePOSTRequest(requestBody);
const request = stringifyAndMakePOSTRequest(requestBody, requestInit);
const sendUrl = new URL(`${apiHost}/api/v1/send`);

const response = await fetch(sendUrl.toString(), request);
Expand Down
4 changes: 3 additions & 1 deletion packages/libs/chainweb-node-client/src/spv.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { ISPVRequestBody, SPVResponse } from './interfaces/PactAPI';
import type { ClientRequestInit } from './local';
import { parseResponseTEXT } from './parseResponseTEXT';
import { stringifyAndMakePOSTRequest } from './stringifyAndMakePOSTRequest';
import { fetch } from './utils/fetch';
Expand All @@ -14,8 +15,9 @@ import { fetch } from './utils/fetch';
export async function spv(
requestBody: ISPVRequestBody,
apiHost: string,
requestInit?: ClientRequestInit,
): Promise<SPVResponse | Response> {
const request = stringifyAndMakePOSTRequest(requestBody);
const request = stringifyAndMakePOSTRequest(requestBody, requestInit);
const spvUrl = new URL(`${apiHost}/spv`);

const response = await fetch(spvUrl.toString(), request);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
import type { ClientRequestInit } from './local';

/**
* Formats API request body to use with `fetch` function.
*
* Corresponds to `mkReq` function:
* https://github.com/kadena-io/pact-lang-api/blob/master/pact-lang-api.js#L533
* @alpha
*/
export function stringifyAndMakePOSTRequest<T>(body: T): object {
export function stringifyAndMakePOSTRequest<T>(
body: T,
requestInit?: ClientRequestInit,
) {
return {
...requestInit,
headers: {
'Content-Type': 'application/json',
...requestInit?.headers,
},
method: 'POST',
body: JSON.stringify(body),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,18 @@ test('should stringify body and create POST request', () => {

expect(expected).toEqual(actual);
});

test('should stringify body and create POST request and add options', () => {
const body: object = { name: 'hello', val: "'world'" };
const actual = stringifyAndMakePOSTRequest<object>(body, { keepalive: true });
const expected = {
headers: {
'Content-Type': 'application/json',
},
keepalive: true,
method: 'POST',
body: '{"name":"hello","val":"\'world\'"}',
};

expect(expected).toEqual(actual);
});
Loading
Loading