Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/eighty-cars-arrive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@rest-hooks/rest': minor
---

Add RestEndpoint in @rest-hooks/rest/next - has async getRequestInit and getHeaders
63 changes: 61 additions & 2 deletions docs/rest/api/RestEndpoint.md
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,8 @@ const getReactSite = new RestEndpoint({
});

getReactSite({ slug: 'cool', isReact: true });
getReactSite.url({ slug: 'cool', isReact: true }) === 'https://site.com/cool?isReact=true';
getReactSite.url({ slug: 'cool', isReact: true }) ===
'https://site.com/cool?isReact=true';
```

</TypeScriptEditor>
Expand Down Expand Up @@ -456,6 +457,35 @@ to indicate there is no body.
Prepares [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch) used in fetch.
This is sent to [fetchResponse](#fetchResponse)

:::tip async

Import from `@rest-hooks/rest/next` to get the next version, which is `async`

<TypeScriptEditor>

```ts
import { RestEndpoint, RestGenerics } from '@rest-hooks/rest/next';

export default class AuthdEndpoint<
O extends RestGenerics = any,
> extends RestEndpoint<O> {
async getRequestInit(body) {
return {
...super.getRequestInit(body),
method: await getMethod(),
};
}
}

async function getMethod() {
return 'GET';
}
```

</TypeScriptEditor>

:::

### getHeaders(headers: HeadersInit): HeadersInit {#getHeaders}

Called by [getRequestInit](#getRequestInit) to determine [HTTP Headers](https://developer.mozilla.org/en-US/docs/Web/API/Request/headers)
Expand All @@ -468,6 +498,35 @@ Don't use hooks here.

:::

:::tip async

Import from `@rest-hooks/rest/next` to get the next version, which is `async`

<TypeScriptEditor>

```ts
import { RestEndpoint, RestGenerics } from '@rest-hooks/rest/next';

export default class AuthdEndpoint<
O extends RestGenerics = any,
> extends RestEndpoint<O> {
async getHeaders(headers: HeadersInit) {
return {
...headers,
'Access-Token': await getAuthToken(),
};
}
}

async function getAuthToken() {
return 'example';
}
```

</TypeScriptEditor>

:::

## Handle fetch

### fetchResponse(input, init): Promise {#fetchResponse}
Expand Down Expand Up @@ -685,7 +744,7 @@ Serializes the parameters. This is used to build a lookup key in global stores.
Default:

```typescript
`${this.method} ${this.url(urlParams)}`
`${this.method} ${this.url(urlParams)}`;
```

## testKey(key): boolean {#testKey}
Expand Down
48 changes: 47 additions & 1 deletion docs/rest/guides/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ defaultValue="static"
values={[
{ label: 'static member', value: 'static' },
{ label: 'function singleton', value: 'function' },
{ label: 'async function', value: 'async' },
]}>
<TabItem value="static">

Expand All @@ -63,7 +64,7 @@ export default class AuthdEndpoint<
// highlight-next-line
declare static accessToken?: string;

getHeaders(headers: HeadersInit): HeadersInit {
getHeaders(headers: HeadersInit) {
return {
...headers,
// highlight-next-line
Expand Down Expand Up @@ -93,6 +94,51 @@ function Auth() {
}
```

</TabItem>
<TabItem value="async">

We'll grab RestEndpoint from `@rest-hooks/rest/next` as this version supports
async `getHeaders`. `@rest-hooks/rest@8` will have these changes.

```ts title="api/AuthdEndpoint.ts"
import { getAuthToken } from 'authorization-singleton';
// highlight-next-line
import { RestEndpoint } from '@rest-hooks/rest/next';

export default class AuthdEndpoint<
O extends RestGenerics = any,
> extends RestEndpoint<O> {
async getHeaders(headers: HeadersInit) {
return {
...headers,
// highlight-next-line
'Access-Token': await getAuthToken(),
};
}
}
```

Upon login we set the token:

```tsx title="Auth.tsx"
import { setAuthToken } from 'authorization-singleton';
import AuthdResource from 'resources/AuthdResource';

function Auth() {
const handleLogin = useCallback(
async e => {
const { accessToken } = await login(new FormData(e.target));
// success!
// highlight-next-line
setAuthToken(accessToken);
},
[login],
);

return <AuthForm onSubmit={handleLogin} />;
}
```

</TabItem>
<TabItem value="function">

Expand Down
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const baseConfig = {
'packages/graphql',
'packages/redux',
'packages/ssr',
'packages/rest/src/next',
'packages/legacy/src/resource',
'packages/legacy/src/rest-3',
'packages/rest-hooks/src/hooks/hasUsableData',
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
"build:types": "yarn build:copy:ambient && tsc --build && yarn workspaces foreach -pti --no-private run build:legacy-types",
"ci:build:types": "yarn build:copy:ambient && tsc --build && yarn workspaces foreach -ptivR --from @rest-hooks/react --from @rest-hooks/rest --from @rest-hooks/graphql --from @rest-hooks/hooks run build:legacy-types",
"ci:build": "yarn workspaces foreach -ptivR --from @rest-hooks/react --from @rest-hooks/rest --from @rest-hooks/graphql --from @rest-hooks/hooks --from @rest-hooks/test run build:lib && yarn workspace @rest-hooks/test run build:bundle && yarn workspace @rest-hooks/normalizr run build:js:node && yarn workspace @rest-hooks/endpoint run build:js:node",
"build:copy:ambient": "mkdirp ./packages/endpoint/lib && copyfiles --flat ./packages/endpoint/src/schema.d.ts ./packages/endpoint/lib/ && copyfiles --flat ./packages/endpoint/src/endpoint.d.ts ./packages/endpoint/lib/&& mkdirp ./packages/core/lib && copyfiles --flat ./packages/core/src/state/RIC.d.ts ./packages/core/lib/state && mkdirp ./packages/experimental/lib && copyfiles --flat ./packages/experimental/src/rest/RestEndpoint.d.ts ./packages/experimental/lib/rest && copyfiles --flat ./packages/rest/src/RestEndpoint.d.ts ./packages/rest/lib",
"copy:websitetypes": "cp ./packages/rest-hooks/index.d.ts ./website/src/components/Playground/editor-types/rest-hooks.d.ts && cp ./packages/core/index.d.ts ./website/src/components/Playground/editor-types/@rest-hooks/core.d.ts && cp ./packages/endpoint/index.d.ts ./website/src/components/Playground/editor-types/@rest-hooks/endpoint.d.ts && cp ./packages/graphql/index.d.ts ./website/src/components/Playground/editor-types/@rest-hooks/graphql.d.ts && cp ./packages/hooks/index.d.ts ./website/src/components/Playground/editor-types/@rest-hooks/hooks.d.ts && cp ./packages/normalizr/index.d.ts ./website/src/components/Playground/editor-types/@rest-hooks/normalizr.d.ts && cp ./packages/react/index.d.ts ./website/src/components/Playground/editor-types/@rest-hooks/react.d.ts && cp ./packages/rest/index.d.ts ./website/src/components/Playground/editor-types/@rest-hooks/rest.d.ts",
"build:copy:ambient": "mkdirp ./packages/endpoint/lib && copyfiles --flat ./packages/endpoint/src/schema.d.ts ./packages/endpoint/lib/ && copyfiles --flat ./packages/endpoint/src/endpoint.d.ts ./packages/endpoint/lib/&& mkdirp ./packages/core/lib && copyfiles --flat ./packages/core/src/state/RIC.d.ts ./packages/core/lib/state && mkdirp ./packages/experimental/lib && copyfiles --flat ./packages/experimental/src/rest/RestEndpoint.d.ts ./packages/experimental/lib/rest && copyfiles --flat ./packages/rest/src/RestEndpoint.d.ts ./packages/rest/lib && copyfiles --flat ./packages/rest/src/next/RestEndpoint.d.ts ./packages/rest/lib/next",
"copy:websitetypes": "./scripts/copywebsitetypes.sh",
"test": "NODE_ENV=test NODE_OPTIONS=--experimental-vm-modules jest",
"test:ci": "yarn test --ci",
"test:coverage": "yarn test --coverage --testPathIgnorePatterns=\"packages/(experimental)\"",
Expand Down
1 change: 1 addition & 0 deletions packages/rest/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
/dist
/legacy
/index.d.ts
/next.d.ts
/ts4.1
4 changes: 4 additions & 0 deletions packages/rest/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@
"require": "./dist/index.js",
"default": "./lib/index.js"
},
"./next": {
"types": "./lib/next/index.d.ts",
"default": "./lib/next/index.js"
},
"./package.json": "./package.json"
},
"type": "module",
Expand Down
11 changes: 6 additions & 5 deletions packages/rest/rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import commonjs from 'rollup-plugin-commonjs';
import resolve from 'rollup-plugin-node-resolve';
import babel from 'rollup-plugin-babel';
import json from 'rollup-plugin-json';
import { terser } from 'rollup-plugin-terser';
import commonjs from 'rollup-plugin-commonjs';
import filesize from 'rollup-plugin-filesize';
import json from 'rollup-plugin-json';
import resolve from 'rollup-plugin-node-resolve';
import replace from 'rollup-plugin-replace';
import { terser } from 'rollup-plugin-terser';

import { typeConfig } from '../../rollup-utils';
import pkg from './package.json';
import { typeConfig, typeConfigNext } from '../../rollup-utils';

const dependencies = Object.keys(pkg.dependencies).filter(
dep => !['@babel/runtime'].includes(dep),
Expand Down Expand Up @@ -44,6 +44,7 @@ if (process.env.BROWSERSLIST_ENV !== 'node12') {
],
});
configs.push(typeConfig);
configs.push(typeConfigNext);
} else {
// node-friendly commonjs build
configs.push({
Expand Down
2 changes: 1 addition & 1 deletion packages/rest/src/__tests__/createResource.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ describe('createResource()', () => {
return super.parseResponse(response);
}

getRequestInit(body: any): RequestInit {
getRequestInit(body: any) {
if (typeof body === 'object') {
return super.getRequestInit({ ...body, email: 'always@always.com' });
}
Expand Down
41 changes: 41 additions & 0 deletions packages/rest/src/next/OptionsToFunction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import type { FetchFunction, ResolveType } from '@rest-hooks/endpoint';

import {
PartialRestGenerics,
RestInstance,
RestFetch,
} from './RestEndpoint.js';
import { PathArgs } from '../pathTypes.js';

export type OptionsToFunction<
O extends PartialRestGenerics,
E extends RestInstance & { body?: any },
F extends FetchFunction,
> = 'path' extends keyof O
? RestFetch<
'searchParams' extends keyof O
? O['searchParams'] & PathArgs<Exclude<O['path'], undefined>>
: PathArgs<Exclude<O['path'], undefined>>,
'body' extends keyof O ? O['body'] : E['body'],
O['process'] extends {} ? ReturnType<O['process']> : ResolveType<F>
>
: 'body' extends keyof O
? RestFetch<
'searchParams' extends keyof O
? O['searchParams'] & PathArgs<Exclude<E['path'], undefined>>
: PathArgs<Exclude<E['path'], undefined>>,
O['body'],
O['process'] extends {} ? ReturnType<O['process']> : ResolveType<F>
>
: 'searchParams' extends keyof O
? RestFetch<
O['searchParams'] & PathArgs<Exclude<E['path'], undefined>>,
E['body'],
O['process'] extends {} ? ReturnType<O['process']> : ResolveType<F>
>
: (
this: ThisParameterType<F>,
...args: Parameters<F>
) => Promise<
O['process'] extends {} ? ReturnType<O['process']> : ResolveType<F>
>;
Loading