@application-kit/graphql 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @application-kit/graphql
2
2
 
3
+ ## 0.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - abb4a67: Реестр кодов сообщений `BusinessMessageCodeRegistryInterface` и тип `BusinessMessageCode`: приложение объявляет коды через `declare module '@application-kit/graphql'`.
8
+ **Ломающее:** параметр типа у `BusinessGraphQLError` и `BusinessErrorOptionsInterface` снят, `BusinessErrorTable` получил значение параметра по умолчанию. Потребителю — записать коды в реестр и удалить свои привязки параметра; без записи тип кода `never`, и `new BusinessGraphQLError` не компилируется.
9
+
10
+ ## 0.5.0
11
+
12
+ ### Minor Changes
13
+
14
+ - a3e984e: Вход `/client`: фабрика `createApolloClient` с колбэком ошибки (флаг `SKIP_GLOBAL_ERROR_TOAST` проверяет сама) и `requireApolloData`.
15
+
3
16
  ## 0.4.0
4
17
 
5
18
  ### Minor Changes
package/README.md CHANGED
@@ -19,7 +19,7 @@ Peer-зависимости: `@nestjs/common`, `@nestjs/graphql`, `class-transfo
19
19
  | Вход | Для чего | Тянет |
20
20
  |------|----------|-------|
21
21
  | `@application-kit/graphql` | сервер: ошибки, форматтер, типы листинга | `@nestjs/*`, `class-validator` |
22
- | `@application-kit/graphql/client` | браузер и SSR: чтение `extensions` ответа | только `@apollo/client`, `graphql` (типы) |
22
+ | `@application-kit/graphql/client` | браузер и SSR: сборка клиента, чтение `extensions` ответа | только `@apollo/client`, `graphql` (типы) |
23
23
  | `@application-kit/graphql/nest` | периметр Mercurius-сервера: опции драйвера, окружение, конфиг | `mercurius`, `@nestjs/mercurius` (типы), `@libs-for-dev/nestjs-config-module` |
24
24
  | `@application-kit/graphql/testing` | спеки потребителя: фейк клиента и ошибки ответа | только `@apollo/client` |
25
25
 
@@ -27,7 +27,7 @@ Peer-зависимости: `@nestjs/common`, `@nestjs/graphql`, `class-transfo
27
27
 
28
28
  ## Сервер
29
29
 
30
- - `BusinessGraphQLError<TMessageCode>` — бизнес-ошибка с транспортным кодом (`BAD_USER_INPUT`, `FORBIDDEN`,
30
+ - `BusinessGraphQLError` — бизнес-ошибка с транспортным кодом (`BAD_USER_INPUT`, `FORBIDDEN`,
31
31
  `NOT_FOUND`) и кодом показываемого текста `messageCode`.
32
32
  - `matchBusinessError(table, fallback)` — таблица «класс доменной ошибки → опции ответа», первая подходящая строка.
33
33
  - `formatGraphQLError(error, supportId)` — единая точка форматирования: `HttpException` → `extensions`,
@@ -37,14 +37,33 @@ Peer-зависимости: `@nestjs/common`, `@nestjs/graphql`, `class-transfo
37
37
 
38
38
  ### Словарь кодов сообщений — у приложения
39
39
 
40
- Пакет не знает кодов сообщений: тип кода — параметр без значения по умолчанию. Приложение один раз связывает его
41
- со своим объединением, и неизвестный код перестаёт компилироваться:
40
+ Пакет не знает кодов сообщений: реестр `BusinessMessageCodeRegistryInterface` пуст, и без записи приложения тип кода —
41
+ `never`. Приложение объявляет коды один раз, и неизвестный код перестаёт компилироваться в `BusinessGraphQLError`,
42
+ `BusinessErrorOptionsInterface` и `BusinessErrorTable`:
42
43
 
43
44
  ```ts
44
- type MessageCode = 'signIn.invalidCredentials' | 'profile.notFound'
45
+ declare module '@application-kit/graphql' {
46
+ interface BusinessMessageCodeRegistryInterface {
47
+ 'profile.notFound': true
48
+ 'signIn.invalidCredentials': true
49
+ }
50
+ }
51
+ ```
52
+
53
+ ## Клиент (`/client`)
54
+
55
+ - `createApolloClient({ http, onError })` — клиент Apollo с `InMemoryCache`, `ErrorLink` и `HttpLink`. `http` — опции
56
+ `HttpLink` как есть. `onError(error)` зовётся на каждую ошибку операции, кроме помеченных флагом
57
+ `SKIP_GLOBAL_ERROR_TOAST` в контексте: их показывает сам вызывающий. Вызывающий получает ошибку в любом случае.
58
+ - `requireApolloData(result)` — данные ответа query; `undefined` вместо них — ошибка транспорта.
45
59
 
46
- export class BusinessGraphQLError extends BaseBusinessGraphQLError<MessageCode> {}
47
- export type BusinessErrorOptions = BusinessErrorOptionsInterface<MessageCode>
60
+ ```ts
61
+ export const apolloClient = createApolloClient({
62
+ http: { uri: '/graphql' },
63
+ onError: (error) => {
64
+ showToast(messageCodeFromError(error), supportIdFromError(error))
65
+ },
66
+ })
48
67
  ```
49
68
 
50
69
  ## Сервер Mercurius (`/nest`)
@@ -0,0 +1,8 @@
1
+ import type { ErrorLike } from '@apollo/client/core';
2
+ import { ApolloClient } from '@apollo/client/core';
3
+ import { HttpLink } from '@apollo/client/link/http';
4
+ export interface ApolloClientOptionsInterface {
5
+ http: HttpLink.Options;
6
+ onError(error: ErrorLike): void;
7
+ }
8
+ export declare const createApolloClient: (options: ApolloClientOptionsInterface) => ApolloClient;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createApolloClient = void 0;
4
+ const core_1 = require("@apollo/client/core");
5
+ const error_1 = require("@apollo/client/link/error");
6
+ const http_1 = require("@apollo/client/link/http");
7
+ const request_error_js_1 = require("./request-error.js");
8
+ const createApolloClient = (options) => {
9
+ const errorLink = new error_1.ErrorLink(({ error, operation }) => {
10
+ if (!(0, request_error_js_1.shouldSkipGlobalErrorToast)(operation.getContext())) {
11
+ options.onError(error);
12
+ }
13
+ });
14
+ return new core_1.ApolloClient({
15
+ cache: new core_1.InMemoryCache(),
16
+ link: core_1.ApolloLink.from([errorLink, new http_1.HttpLink(options.http)]),
17
+ });
18
+ };
19
+ exports.createApolloClient = createApolloClient;
@@ -1,4 +1,6 @@
1
+ export * from './create-apollo-client.js';
1
2
  export * from './message-code-from-error.js';
2
3
  export * from './rejected-characters-from-error.js';
3
4
  export * from './request-error.js';
5
+ export * from './require-apollo-data.js';
4
6
  export * from './support-id-from-error.js';
@@ -14,7 +14,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./create-apollo-client.js"), exports);
17
18
  __exportStar(require("./message-code-from-error.js"), exports);
18
19
  __exportStar(require("./rejected-characters-from-error.js"), exports);
19
20
  __exportStar(require("./request-error.js"), exports);
21
+ __exportStar(require("./require-apollo-data.js"), exports);
20
22
  __exportStar(require("./support-id-from-error.js"), exports);
@@ -0,0 +1,3 @@
1
+ export declare const requireApolloData: <Data>(result: {
2
+ data: Data | undefined;
3
+ }) => Data;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.requireApolloData = void 0;
4
+ const requireApolloData = (result) => {
5
+ if (result.data === undefined) {
6
+ throw new Error('No data returned from Apollo Client');
7
+ }
8
+ return result.data;
9
+ };
10
+ exports.requireApolloData = requireApolloData;
@@ -0,0 +1,3 @@
1
+ export type BusinessMessageCode = keyof BusinessMessageCodeRegistryInterface;
2
+ export interface BusinessMessageCodeRegistryInterface {
3
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1 +1,2 @@
1
+ export * from './business-message-code.js';
1
2
  export * from './graphql-error-contract.js';
@@ -14,4 +14,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./business-message-code.js"), exports);
17
18
  __exportStar(require("./graphql-error-contract.js"), exports);
@@ -1,5 +1,6 @@
1
1
  import { GraphQLError } from 'graphql';
2
+ import type { BusinessMessageCode } from '../contract/business-message-code.js';
2
3
  import type { BusinessGraphQLErrorCode, GraphQLErrorWireExtensions } from '../contract/graphql-error-contract.js';
3
- export declare class BusinessGraphQLError<TMessageCode extends string> extends GraphQLError {
4
- constructor(message: string, code: BusinessGraphQLErrorCode, messageCode: TMessageCode, extensions?: GraphQLErrorWireExtensions);
4
+ export declare class BusinessGraphQLError extends GraphQLError {
5
+ constructor(message: string, code: BusinessGraphQLErrorCode, messageCode: BusinessMessageCode, extensions?: GraphQLErrorWireExtensions);
5
6
  }
@@ -1,7 +1,8 @@
1
+ import type { BusinessMessageCode } from '../contract/business-message-code.js';
1
2
  import type { BusinessGraphQLErrorCode } from '../contract/graphql-error-contract.js';
2
- export interface BusinessErrorOptionsInterface<TMessageCode extends string> {
3
+ export interface BusinessErrorOptionsInterface {
3
4
  code: BusinessGraphQLErrorCode;
4
- messageCode: TMessageCode;
5
+ messageCode: BusinessMessageCode;
5
6
  }
6
- export type BusinessErrorTable<TOptions> = readonly [new (...arguments_: never[]) => Error, TOptions][];
7
+ export type BusinessErrorTable<TOptions = BusinessErrorOptionsInterface> = readonly [new (...arguments_: never[]) => Error, TOptions][];
7
8
  export declare const matchBusinessError: <TOptions>(table: BusinessErrorTable<TOptions>, fallback: TOptions) => (commandError: Error) => TOptions;
@@ -0,0 +1,8 @@
1
+ import type { ErrorLike } from '@apollo/client/core';
2
+ import { ApolloClient } from '@apollo/client/core';
3
+ import { HttpLink } from '@apollo/client/link/http';
4
+ export interface ApolloClientOptionsInterface {
5
+ http: HttpLink.Options;
6
+ onError(error: ErrorLike): void;
7
+ }
8
+ export declare const createApolloClient: (options: ApolloClientOptionsInterface) => ApolloClient;
@@ -0,0 +1,15 @@
1
+ import { ApolloClient, ApolloLink, InMemoryCache } from '@apollo/client/core';
2
+ import { ErrorLink } from '@apollo/client/link/error';
3
+ import { HttpLink } from '@apollo/client/link/http';
4
+ import { shouldSkipGlobalErrorToast } from './request-error.js';
5
+ export const createApolloClient = (options) => {
6
+ const errorLink = new ErrorLink(({ error, operation }) => {
7
+ if (!shouldSkipGlobalErrorToast(operation.getContext())) {
8
+ options.onError(error);
9
+ }
10
+ });
11
+ return new ApolloClient({
12
+ cache: new InMemoryCache(),
13
+ link: ApolloLink.from([errorLink, new HttpLink(options.http)]),
14
+ });
15
+ };
@@ -1,4 +1,6 @@
1
+ export * from './create-apollo-client.js';
1
2
  export * from './message-code-from-error.js';
2
3
  export * from './rejected-characters-from-error.js';
3
4
  export * from './request-error.js';
5
+ export * from './require-apollo-data.js';
4
6
  export * from './support-id-from-error.js';
@@ -1,4 +1,6 @@
1
+ export * from './create-apollo-client.js';
1
2
  export * from './message-code-from-error.js';
2
3
  export * from './rejected-characters-from-error.js';
3
4
  export * from './request-error.js';
5
+ export * from './require-apollo-data.js';
4
6
  export * from './support-id-from-error.js';
@@ -0,0 +1,3 @@
1
+ export declare const requireApolloData: <Data>(result: {
2
+ data: Data | undefined;
3
+ }) => Data;
@@ -0,0 +1,6 @@
1
+ export const requireApolloData = (result) => {
2
+ if (result.data === undefined) {
3
+ throw new Error('No data returned from Apollo Client');
4
+ }
5
+ return result.data;
6
+ };
@@ -0,0 +1,3 @@
1
+ export type BusinessMessageCode = keyof BusinessMessageCodeRegistryInterface;
2
+ export interface BusinessMessageCodeRegistryInterface {
3
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1 +1,2 @@
1
+ export * from './business-message-code.js';
1
2
  export * from './graphql-error-contract.js';
@@ -1 +1,2 @@
1
+ export * from './business-message-code.js';
1
2
  export * from './graphql-error-contract.js';
@@ -1,5 +1,6 @@
1
1
  import { GraphQLError } from 'graphql';
2
+ import type { BusinessMessageCode } from '../contract/business-message-code.js';
2
3
  import type { BusinessGraphQLErrorCode, GraphQLErrorWireExtensions } from '../contract/graphql-error-contract.js';
3
- export declare class BusinessGraphQLError<TMessageCode extends string> extends GraphQLError {
4
- constructor(message: string, code: BusinessGraphQLErrorCode, messageCode: TMessageCode, extensions?: GraphQLErrorWireExtensions);
4
+ export declare class BusinessGraphQLError extends GraphQLError {
5
+ constructor(message: string, code: BusinessGraphQLErrorCode, messageCode: BusinessMessageCode, extensions?: GraphQLErrorWireExtensions);
5
6
  }
@@ -1,7 +1,8 @@
1
+ import type { BusinessMessageCode } from '../contract/business-message-code.js';
1
2
  import type { BusinessGraphQLErrorCode } from '../contract/graphql-error-contract.js';
2
- export interface BusinessErrorOptionsInterface<TMessageCode extends string> {
3
+ export interface BusinessErrorOptionsInterface {
3
4
  code: BusinessGraphQLErrorCode;
4
- messageCode: TMessageCode;
5
+ messageCode: BusinessMessageCode;
5
6
  }
6
- export type BusinessErrorTable<TOptions> = readonly [new (...arguments_: never[]) => Error, TOptions][];
7
+ export type BusinessErrorTable<TOptions = BusinessErrorOptionsInterface> = readonly [new (...arguments_: never[]) => Error, TOptions][];
7
8
  export declare const matchBusinessError: <TOptions>(table: BusinessErrorTable<TOptions>, fallback: TOptions) => (commandError: Error) => TOptions;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@application-kit/graphql",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Контракт ошибок GraphQL (сервер и клиент) и типы курсорного листинга для NestJS",
5
5
  "keywords": [
6
6
  "apollo",