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

fix(types): Optional JSON params where undefined is not valid #134

Merged
merged 4 commits into from
Aug 31, 2023
Merged
Changes from 2 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
63 changes: 57 additions & 6 deletions src/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import {
nullable,
number,
object,
omit,
optional,
record,
string,
Expand Down Expand Up @@ -178,16 +177,42 @@ export type JsonRpcError = OptionalField<
>;

export const JsonRpcParamsStruct: Struct<Json[] | Record<string, Json>, null> =
optional(union([record(string(), JsonStruct), array(JsonStruct)])) as any;
union([record(string(), JsonStruct), array(JsonStruct)]);

export type JsonRpcParams = Json[] | Record<string, Json>;

export const JsonRpcRequestStruct = object({
export const JsonRpcRequestStruct: Struct<
{
id: string | number | null;
jsonrpc: '2.0';
method: string;
params?: Json[] | Record<string, Json>;
},
{
id: Struct<string | number | null, null>;
jsonrpc: Struct<'2.0', '2.0'>;
method: Struct<string, null>;
params?: Struct<Json[] | Record<string, Json>, null>;
}
> = object({
id: JsonRpcIdStruct,
jsonrpc: JsonRpcVersionStruct,
method: string(),
params: JsonRpcParamsStruct,
});
params: optional(JsonRpcParamsStruct),
}) as Struct<
{
id: string | number | null;
jsonrpc: '2.0';
method: string;
params?: Json[] | Record<string, Json>;
},
{
id: Struct<string | number | null, null>;
jsonrpc: Struct<'2.0', '2.0'>;
method: Struct<string, null>;
params?: Struct<Json[] | Record<string, Json>, null>;
}
>;

export type InferWithParams<
Type extends Struct<any>,
Expand All @@ -207,7 +232,33 @@ export type InferWithParams<
export type JsonRpcRequest<Params extends JsonRpcParams = JsonRpcParams> =
InferWithParams<typeof JsonRpcRequestStruct, Params>;

export const JsonRpcNotificationStruct = omit(JsonRpcRequestStruct, ['id']);
export const JsonRpcNotificationStruct: Struct<
{
jsonrpc: '2.0';
method: string;
params?: Json[] | Record<string, Json>;
},
{
jsonrpc: Struct<'2.0', '2.0'>;
method: Struct<string, null>;
params?: Struct<Json[] | Record<string, Json>, null>;
}
> = object({
jsonrpc: JsonRpcVersionStruct,
method: string(),
params: optional(JsonRpcParamsStruct),
}) as Struct<
{
jsonrpc: '2.0';
method: string;
params?: Json[] | Record<string, Json>;
},
{
jsonrpc: Struct<'2.0', '2.0'>;
method: Struct<string, null>;
params?: Struct<Json[] | Record<string, Json>, null>;
}
>;

/**
* A JSON-RPC notification object.
Expand Down