Skip to content

feat: RestApiClient example #68

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

Merged
merged 3 commits into from
Aug 5, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,40 @@ myBase.myMethod();
myBase.myProperty;
```

### TypeScript for a customized Base class

If you write your `d.ts` files by hand instead of generating them from TypeScript source code, you can use the `ExtendBaseWith` Generic to create a class with custom defaults and plugins. It can even inherit from another customized class.

```ts
import { Base, ExtendBaseWith } from "../../index.js";

import { myPlugin } from "./my-plugin.js";

export const MyBase: ExtendBaseWith<
Base,
{
defaults: {
myPluginOption: string;
};
plugins: [typeof myPlugin];
}
>;

// support using the `MyBase` import to be used as a class instance type
export type MyBase = typeof MyBase;
```

The last line is important in order to make `MyBase` behave like a class type, making the following code possible:

```ts
import { MyBase } from "./index.js";

export async function testInstanceType(client: MyBase) {
// types set correctly on `client`
client.myPlugin({ myPluginOption: "foo" });
}
```

### Defaults

TypeScript will not complain when chaining `.withDefaults()` calls endlessly: the static `.defaults` property will be set correctly. However, when instantiating from a class with 4+ chained `.withDefaults()` calls, then only the defaults from the first 3 calls are supported. See [#57](https://github.com/gr2m/javascript-plugin-architecture-with-typescript-definitions/pull/57) for details.
Expand Down
20 changes: 20 additions & 0 deletions examples/rest-api-client-dts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Custom class with defaults and plugins (TypeScript Declaration example)

This example does not implement any code, it's meant as a reference for types only.

Usage example:

```js
import { RestApiClient } from "javascript-plugin-architecture-with-typescript-definitions/examples/rest-api-client-dts";

const client = new RestApiClient({
baseUrl: "https://api.github.com",
userAgent: "my-app/1.0.0",
headers: {
authorization: "token ghp_aB3...",
},
});

const { data } = await client.request("GET /user");
console.log("You are logged in as %s", data.login);
```
15 changes: 15 additions & 0 deletions examples/rest-api-client-dts/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Base, ExtendBaseWith } from "../../index.js";

import { requestPlugin } from "./request-plugin.js";

export const RestApiClient: ExtendBaseWith<
Base,
{
defaults: {
userAgent: string;
};
plugins: [typeof requestPlugin];
}
>;

export type RestApiClient = typeof RestApiClient;
5 changes: 5 additions & 0 deletions examples/rest-api-client-dts/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Base } from "../../index.js";

export const RestApiClient = Base.withPlugins([requestPlugin]).withDefaults({
userAgent: "rest-api-client/1.0.0",
});
54 changes: 54 additions & 0 deletions examples/rest-api-client-dts/index.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { expectType } from "tsd";

import { RestApiClient } from "./index.js";

// @ts-expect-error - An argument for 'options' was not provided
let value: typeof RestApiClient = new RestApiClient();

expectType<{ userAgent: string }>(value.defaults);

expectType<{ userAgent: string }>(RestApiClient.defaults);

// @ts-expect-error - Type '{}' is missing the following properties from type 'Options': myRequiredUserOption
new RestApiClient({});

new RestApiClient({
baseUrl: "https://api.github.com",
userAgent: "my-app/v1.0.0",
});

export async function test() {
const client = new RestApiClient({
baseUrl: "https://api.github.com",
headers: {
authorization: "token 123456789",
},
});

expectType<
Promise<{
status: number;
headers: Record<string, string>;
data?: Record<string, unknown>;
}>
>(client.request(""));

const getUserResponse = await client.request("GET /user");
expectType<{
status: number;
headers: Record<string, string>;
data?: Record<string, unknown>;
}>(getUserResponse);

client.request("GET /repos/{owner}/{repo}", {
owner: "gr2m",
repo: "javascript-plugin-architecture-with-typescript-definitions",
});
}

export async function testInstanceType(client: RestApiClient) {
client.request("GET /repos/{owner}/{repo}", {
owner: "gr2m",
repo: "javascript-plugin-architecture-with-typescript-definitions",
});
}
48 changes: 48 additions & 0 deletions examples/rest-api-client-dts/request-plugin.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Base } from "../../index.js";

declare module "../.." {
namespace Base {
interface Options {
/**
* Base URL for all http requests
*/
baseUrl: string;

/**
* Set a custom user agent. Defaults to "rest-api-client/1.0.0"
*/
userAgent?: string;

/**
* Optional http request headers that will be set on all requsets
*/
headers?: {
authorization?: string;
accept?: string;
[key: string]: string | undefined;
};
}
}
}

interface Response {
status: number;
headers: Record<string, string>;
data?: Record<string, unknown>;
}

interface Parameters {
headers?: Record<string, string>;
[parameter: string]: unknown;
}

interface RequestInterface {
(route: string, parameters?: Parameters): Promise<Response>;
}

export declare function requestPlugin(
base: Base,
options: Base.Options
): {
request: RequestInterface;
};
12 changes: 12 additions & 0 deletions examples/rest-api-client-dts/request-plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* This example does not implement any logic, it's just meant as
* a reference for its types
*
* @param {Base} base
* @param {Base.Options} options
*/
export function requestPlugin(base, options) {
return {
async request(route, parameters) {},
};
}
30 changes: 26 additions & 4 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,7 @@ type RequiredIfRemaining<PredefinedOptions, NowProvided> = NonOptionalKeys<
NowProvided
];

type ConstructorRequiringOptionsIfNeeded<
Class extends ClassWithPlugins,
PredefinedOptions
> = {
type ConstructorRequiringOptionsIfNeeded<Class, PredefinedOptions> = {
defaults: PredefinedOptions;
} & {
new <NowProvided>(
Expand Down Expand Up @@ -156,4 +153,29 @@ export declare class Base<TOptions extends Base.Options = Base.Options> {

constructor(options: TOptions);
}

type Extensions = {
defaults?: {};
plugins?: Plugin[];
};

type OrObject<T, Extender> = T extends Extender ? {} : T;

type ApplyPlugins<Plugins extends Plugin[] | undefined> =
Plugins extends Plugin[]
? UnionToIntersection<ReturnType<Plugins[number]>>
: {};

export type ExtendBaseWith<
BaseClass extends Base,
BaseExtensions extends Extensions
> = BaseClass &
ConstructorRequiringOptionsIfNeeded<
BaseClass & ApplyPlugins<BaseExtensions["plugins"]>,
OrObject<BaseClass["options"], unknown>
> &
ApplyPlugins<BaseExtensions["plugins"]> & {
defaults: OrObject<BaseExtensions["defaults"], undefined>;
};

export {};
47 changes: 46 additions & 1 deletion index.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expectType } from "tsd";
import { Base, Plugin } from "./index.js";
import { Base, ExtendBaseWith, Plugin } from "./index.js";

import { fooPlugin } from "./plugins/foo/index.js";
import { barPlugin } from "./plugins/bar/index.js";
Expand Down Expand Up @@ -238,3 +238,48 @@ const baseWithManyChainedDefaultsAndPlugins =
expectType<string>(baseWithManyChainedDefaultsAndPlugins.foo);
expectType<string>(baseWithManyChainedDefaultsAndPlugins.bar);
expectType<string>(baseWithManyChainedDefaultsAndPlugins.getFooOption());

declare const RestApiClient: ExtendBaseWith<
Base,
{
defaults: {
defaultValue: string;
};
plugins: [
() => { pluginValueOne: number },
() => { pluginValueTwo: boolean }
];
}
>;

expectType<string>(RestApiClient.defaults.defaultValue);

// @ts-expect-error
RestApiClient.defaults.unexpected;

expectType<number>(RestApiClient.pluginValueOne);
expectType<boolean>(RestApiClient.pluginValueTwo);

// @ts-expect-error
RestApiClient.unexpected;

declare const MoreDefaultRestApiClient: ExtendBaseWith<
typeof RestApiClient,
{
defaults: {
anotherDefaultValue: number;
};
}
>;

expectType<string>(MoreDefaultRestApiClient.defaults.defaultValue);
expectType<number>(MoreDefaultRestApiClient.defaults.anotherDefaultValue);

declare const MorePluginRestApiClient: ExtendBaseWith<
typeof MoreDefaultRestApiClient,
{
plugins: [() => { morePluginValue: string[] }];
}
>;

expectType<string[]>(MorePluginRestApiClient.morePluginValue);
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"test": "npm run -s test:code && npm run -s test:typescript && npm run -s test:coverage && npm run -s lint",
"test:code": "c8 uvu . '^(examples/.*/)?test.js$'",
"test:coverage": "c8 check-coverage",
"test:typescript": "tsd && tsd examples/*"
"test:typescript": "tsd && for d in examples/* ; do tsd $d; done"
},
"repository": "github:gr2m/javascript-plugin-architecture-with-typescript-definitions",
"keywords": [
Expand Down