@metarisc/metarisc-js 0.0.1-alpha.24 → 0.0.1-alpha.26

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.
Files changed (72) hide show
  1. package/README.md +46 -6
  2. package/lib/api/FeedAPI.d.ts +1 -1
  3. package/lib/api/FeedAPI.js +1 -1
  4. package/lib/api/MoiAPI.d.ts +11 -0
  5. package/lib/api/MoiAPI.js +27 -0
  6. package/lib/api/SupportAPI.js +1 -1
  7. package/lib/api/UtilisateursAPI.d.ts +10 -0
  8. package/lib/api/UtilisateursAPI.js +28 -0
  9. package/lib/auth/oauth2.d.ts +46 -8
  10. package/lib/auth/oauth2.js +41 -10
  11. package/lib/client.d.ts +23 -5
  12. package/lib/client.js +78 -40
  13. package/lib/core.d.ts +4 -13
  14. package/lib/core.js +5 -2
  15. package/lib/index.d.ts +4 -4
  16. package/lib/index.js +6 -3
  17. package/lib/metarisc.d.ts +4 -2
  18. package/lib/metarisc.js +5 -2
  19. package/lib/model/Moi200Response.d.ts +12 -0
  20. package/lib/utils.d.ts +1 -0
  21. package/lib/utils.js +12 -3
  22. package/package.json +1 -1
  23. package/src/api/FeedAPI.ts +1 -1
  24. package/src/api/MoiAPI.ts +27 -0
  25. package/src/api/SupportAPI.ts +1 -1
  26. package/src/api/UtilisateursAPI.ts +32 -0
  27. package/src/auth/oauth2.ts +95 -11
  28. package/src/client.ts +157 -124
  29. package/src/core.ts +33 -39
  30. package/src/index.ts +6 -4
  31. package/src/metarisc.ts +13 -6
  32. package/src/model/Moi200Response.ts +12 -0
  33. package/src/utils.ts +18 -11
  34. package/lib/api/OrganisationAPI.d.ts +0 -19
  35. package/lib/api/OrganisationAPI.js +0 -43
  36. package/lib/api/POIAPI.d.ts +0 -50
  37. package/lib/api/POIAPI.js +0 -106
  38. package/lib/model/Feature.d.ts +0 -6
  39. package/lib/model/FeatureGeometry.d.ts +0 -5
  40. package/lib/model/FeatureGeometry.js +0 -2
  41. package/lib/model/GetEvenement404Response.d.ts +0 -6
  42. package/lib/model/GetEvenement404Response.js +0 -2
  43. package/lib/model/GetFeature200Response.d.ts +0 -7
  44. package/lib/model/GetFeature200Response.js +0 -2
  45. package/lib/model/GetFeature200ResponseCrs.d.ts +0 -5
  46. package/lib/model/GetFeature200ResponseCrs.js +0 -2
  47. package/lib/model/GetFeature200ResponseCrsProperties.d.ts +0 -3
  48. package/lib/model/GetFeature200ResponseCrsProperties.js +0 -2
  49. package/lib/model/POI.d.ts +0 -13
  50. package/lib/model/POI.js +0 -2
  51. package/lib/model/POIReferencesExterieuresInner.d.ts +0 -4
  52. package/lib/model/POIReferencesExterieuresInner.js +0 -2
  53. package/lib/model/PatchPoiRequest.d.ts +0 -3
  54. package/lib/model/PatchPoiRequest.js +0 -2
  55. package/lib/model/SuiviAdministratif.d.ts +0 -6
  56. package/lib/model/SuiviAdministratif.js +0 -2
  57. package/lib/model/Utilisateur1.d.ts +0 -3
  58. package/lib/model/Utilisateur1.js +0 -2
  59. package/src/api/OrganisationAPI.ts +0 -46
  60. package/src/api/POIAPI.ts +0 -124
  61. package/src/model/Feature.ts +0 -7
  62. package/src/model/FeatureGeometry.ts +0 -5
  63. package/src/model/GetEvenement404Response.ts +0 -6
  64. package/src/model/GetFeature200Response.ts +0 -8
  65. package/src/model/GetFeature200ResponseCrs.ts +0 -6
  66. package/src/model/GetFeature200ResponseCrsProperties.ts +0 -3
  67. package/src/model/POI.ts +0 -14
  68. package/src/model/POIReferencesExterieuresInner.ts +0 -4
  69. package/src/model/PatchPoiRequest.ts +0 -3
  70. package/src/model/SuiviAdministratif.ts +0 -6
  71. package/src/model/Utilisateur1.ts +0 -3
  72. /package/lib/model/{Feature.js → Moi200Response.js} +0 -0
package/README.md CHANGED
@@ -1,4 +1,3 @@
1
-
2
1
  # Metarisc JS
3
2
 
4
3
  La librairie Metarisc JS offre un accès simple et pratique à l'API Metarisc à partir d'applications écrites en langage JS. Elle comprend un ensemble de classes et de fonctions pour l'ensemble des ressources de l'API.
@@ -13,20 +12,61 @@ npm i @metarisc/metarisc-js
13
12
 
14
13
  Pour utiliser la librairie, il suffit de l'importer comme ceci :
15
14
 
16
- ```php
17
- import { Metarisc } from '@metarisc/metarisc-js';';
15
+ ```ts
16
+ import { Metarisc } from '@metarisc/metarisc-js';
18
17
  ```
19
18
 
20
19
  ## Utilisation
21
20
 
22
21
  ### Requêtes
23
22
 
24
- Pour effectuer une requête sur Metarisc, qu'elle soit simple ou paginés (voir la [documentation](http://metarisc.fr/docs/api/#/#pagination)), faites de cette manière :
23
+ Pour effectuer une requête sur Metarisc, il faut tout d'adord initialisé le client metarisc de cette manière :
24
+
25
+ ```ts
26
+ const m = new Metarisc({
27
+ metarisc_url: "https://api.metarisc.fr",
28
+ client_id: "CLIENT_ID",
29
+ client_secret: "CLIENT_SECRET"
30
+ });
31
+
32
+ m.dossiers.getDossier("123456");
33
+ ```
34
+
35
+ Ensuite vous pouvez faire vos requêtes.
36
+
37
+ #### Requêtes simple
38
+
39
+ Pour faire un appel API après initialisation du client, vous pouvez utiliser l'accès rapide à l'API souhaitée.
40
+
41
+ Exemple :
42
+
43
+ ```ts
44
+ m.dossiers.getDossier("123456");
45
+ ```
46
+
47
+ Le type de retour d'une requête simple est :
48
+
49
+ ```ts
50
+ Promise<AxiosResponse<T>>;
51
+ ```
52
+
53
+ (voir les documentations suivantes [Promise](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Promise) et [AxiosResponse](https://axios-http.com/docs/res_schema))
54
+
55
+ #### Requêtes paginées
56
+
57
+ Pour récupérer des résultats paginés Metarisc (voir la [documentation](http://metarisc.fr/docs/api/#/#pagination)), il suffit de faire appel à l'api souhaitée de la même manière que pour une requête simple.
25
58
 
26
59
  Exemple :
27
60
 
28
61
  ```ts
29
62
  const m = new Metarisc(config);
30
- m.NotificationsAPI.getNotification('123456');
31
63
  m.NotificationsAPI.paginateNotifications();
32
- ```
64
+ ```
65
+
66
+ Le type de retour d'une requête paginée est :
67
+
68
+ ```ts
69
+ AsyncGenerator<T>;
70
+ ```
71
+
72
+ (voir la documentation suivante [AsyncGenerator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator))
@@ -7,5 +7,5 @@ export declare class FeedAPI extends Core {
7
7
  /**
8
8
  * Récupération d'une liste de message composant un flux d'activité pour l'utilisateur connecté.
9
9
  */
10
- getFeedMessages(): Collection<FeedMessage>;
10
+ paginateFeedMessages(): Collection<FeedMessage>;
11
11
  }
@@ -13,7 +13,7 @@ class FeedAPI extends core_1.Core {
13
13
  /**
14
14
  * Récupération d'une liste de message composant un flux d'activité pour l'utilisateur connecté.
15
15
  */
16
- getFeedMessages() {
16
+ paginateFeedMessages() {
17
17
  const pathVariable = {};
18
18
  return this.collect({
19
19
  method: 'GET',
@@ -0,0 +1,11 @@
1
+ import { Core, MetariscConfig } from "../core";
2
+ import type { AxiosResponse } from "axios";
3
+ import { Client } from "../client";
4
+ import { Moi200Response } from '../model/Moi200Response';
5
+ export declare class MoiAPI extends Core {
6
+ constructor(config: MetariscConfig, client?: Client);
7
+ /**
8
+ * Récupérer les détails de l'utilisateur connecté.
9
+ */
10
+ moi(): Promise<AxiosResponse<Moi200Response>>;
11
+ }
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MoiAPI = void 0;
7
+ const core_1 = require("../core");
8
+ const utils_1 = __importDefault(require("../utils"));
9
+ class MoiAPI extends core_1.Core {
10
+ constructor(config, client) {
11
+ super(config, client);
12
+ }
13
+ /**
14
+ * Récupérer les détails de l'utilisateur connecté.
15
+ */
16
+ async moi() {
17
+ const pathVariable = {};
18
+ return this.request({
19
+ method: 'GET',
20
+ endpoint: utils_1.default.constructPath(pathVariable, '/@moi'),
21
+ headers: {},
22
+ params: {},
23
+ body: {}
24
+ });
25
+ }
26
+ }
27
+ exports.MoiAPI = MoiAPI;
@@ -35,7 +35,7 @@ class SupportAPI extends core_1.Core {
35
35
  method: 'GET',
36
36
  endpoint: utils_1.default.constructPath(pathVariable, '/support/'),
37
37
  headers: {},
38
- params: { 'page': page.toString(), 'per_page': perPage.toString() },
38
+ params: { 'page': page?.toString(), 'per_page': perPage?.toString() },
39
39
  body: {}
40
40
  });
41
41
  }
@@ -6,6 +6,11 @@ import { Utilisateur } from '../model/Utilisateur';
6
6
  import { Email } from '../model/Email';
7
7
  export declare class UtilisateursAPI extends Core {
8
8
  constructor(config: MetariscConfig, client?: Client);
9
+ /**
10
+ * Retourne un utilisateur Metarisc.
11
+ * @param utilisateurId
12
+ */
13
+ getUtilisateurDetails(utilisateurId: string): Promise<AxiosResponse<Utilisateur>>;
9
14
  /**
10
15
  * L'utilisateur connecté retourné par ce point de terminaison utilise le token d'accès généré par le service OpenID Connect afin de le lier à une identité connue de Metarisc. Si l'utilisateur est inconnu une erreur est retournée.
11
16
  */
@@ -16,4 +21,9 @@ export declare class UtilisateursAPI extends Core {
16
21
  * @param perPage Nombre de résultats demandé
17
22
  */
18
23
  paginateMoiEmails(page?: number, perPage?: number): Collection<Email>;
24
+ /**
25
+ * Retourne une liste des adresses mail publiques d'un utilisateur.
26
+ * @param utilisateurId
27
+ */
28
+ paginateUtilisateurEmails(utilisateurId: string): Collection<Email>;
19
29
  }
@@ -10,6 +10,20 @@ class UtilisateursAPI extends core_1.Core {
10
10
  constructor(config, client) {
11
11
  super(config, client);
12
12
  }
13
+ /**
14
+ * Retourne un utilisateur Metarisc.
15
+ * @param utilisateurId
16
+ */
17
+ async getUtilisateurDetails(utilisateurId) {
18
+ const pathVariable = { 'utilisateur_id': utilisateurId };
19
+ return this.request({
20
+ method: 'GET',
21
+ endpoint: utils_1.default.constructPath(pathVariable, '/utilisateurs/{utilisateur_id}'),
22
+ headers: {},
23
+ params: {},
24
+ body: {}
25
+ });
26
+ }
13
27
  /**
14
28
  * L'utilisateur connecté retourné par ce point de terminaison utilise le token d'accès généré par le service OpenID Connect afin de le lier à une identité connue de Metarisc. Si l'utilisateur est inconnu une erreur est retournée.
15
29
  */
@@ -38,5 +52,19 @@ class UtilisateursAPI extends core_1.Core {
38
52
  body: {}
39
53
  });
40
54
  }
55
+ /**
56
+ * Retourne une liste des adresses mail publiques d'un utilisateur.
57
+ * @param utilisateurId
58
+ */
59
+ paginateUtilisateurEmails(utilisateurId) {
60
+ const pathVariable = { 'utilisateur_id': utilisateurId };
61
+ return this.collect({
62
+ method: 'GET',
63
+ endpoint: utils_1.default.constructPath(pathVariable, '/utilisateurs/{utilisateur_id}/emails'),
64
+ headers: {},
65
+ params: {},
66
+ body: {}
67
+ });
68
+ }
41
69
  }
42
70
  exports.UtilisateursAPI = UtilisateursAPI;
@@ -1,19 +1,57 @@
1
- import { OAuth2Options } from "../core";
1
+ export interface OAuth2Options {
2
+ client_id?: string;
3
+ client_secret?: string;
4
+ response_type?: string;
5
+ redirect_uri?: string;
6
+ state?: string;
7
+ code?: string;
8
+ scope?: string;
9
+ [name: string]: string;
10
+ }
11
+ export interface GrantResponse {
12
+ access_token?: string;
13
+ expires_in?: number;
14
+ id_token?: string;
15
+ refresh_token?: string;
16
+ refresh_expires_in?: number;
17
+ session_state?: string;
18
+ token_type?: string;
19
+ error?: string;
20
+ error_description?: string;
21
+ }
22
+ export interface RefreshResponse {
23
+ access_token: string;
24
+ token_type: string;
25
+ expires_in?: number;
26
+ refresh_token?: string;
27
+ scope?: string;
28
+ }
2
29
  export declare class OAuth2 {
3
30
  static AUTHORIZATION_URL: string;
4
31
  static ACCESS_TOKEN_URL: string;
32
+ private options;
5
33
  /**
6
34
  * Utilisation d'OAuth2 pour récupérer un access token utilisable dans Metarisc.
7
- *
8
- * La configuration doit contenir au moins :
9
- * - CLIENT_ID (Le client_id de l'application inscrite sur Metarisc ID pour communiquer avec Metarisc)
10
- * - CLIENT_SECRET (Le client_secret de l'application inscrite sur Metarisc ID pour communiquer avec Metarisc)
11
- *
12
- * La configuration peut contenir aussi :
13
- * - ACCESS_TOKEN_URL
14
35
  **/
36
+ constructor(options: OAuth2Options);
15
37
  /**
16
38
  * OAuth2 Authorize URL Generator helper.
17
39
  */
18
40
  static authorizeUrl(options: OAuth2Options): string;
41
+ /**
42
+ * OAuth2 Authorize URL Generator helper.
43
+ */
44
+ authorizeUrl(): string;
45
+ /**
46
+ * Initie le flow Authorization Code https://datatracker.ietf.org/doc/html/rfc6749#section-4.1
47
+ */
48
+ getAuthorizationCode(custom?: OAuth2Options): Promise<GrantResponse>;
49
+ /**
50
+ * Initie le flow Client Credentials https://datatracker.ietf.org/doc/html/rfc6749#section-4.4
51
+ */
52
+ getClientCredentials(custom?: OAuth2Options): Promise<GrantResponse>;
53
+ /**
54
+ * Refresh Token (https://datatracker.ietf.org/doc/html/rfc6749#section-1.5)
55
+ */
56
+ refreshToken(refresh_token: string, custom?: OAuth2Options): Promise<RefreshResponse>;
19
57
  }
@@ -1,25 +1,56 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.OAuth2 = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const axios_oauth_client_1 = __importDefault(require("axios-oauth-client"));
4
9
  class OAuth2 {
5
10
  /**
6
11
  * Utilisation d'OAuth2 pour récupérer un access token utilisable dans Metarisc.
7
- *
8
- * La configuration doit contenir au moins :
9
- * - CLIENT_ID (Le client_id de l'application inscrite sur Metarisc ID pour communiquer avec Metarisc)
10
- * - CLIENT_SECRET (Le client_secret de l'application inscrite sur Metarisc ID pour communiquer avec Metarisc)
11
- *
12
- * La configuration peut contenir aussi :
13
- * - ACCESS_TOKEN_URL
14
12
  **/
13
+ constructor(options) {
14
+ this.options = options;
15
+ }
15
16
  /**
16
17
  * OAuth2 Authorize URL Generator helper.
17
18
  */
18
19
  static authorizeUrl(options) {
19
- const params = new URLSearchParams(options);
20
+ return (new OAuth2(options)).authorizeUrl();
21
+ }
22
+ /**
23
+ * OAuth2 Authorize URL Generator helper.
24
+ */
25
+ authorizeUrl() {
26
+ const params = new URLSearchParams(this.options);
20
27
  return OAuth2.AUTHORIZATION_URL + '?' + params.toString();
21
28
  }
29
+ /**
30
+ * Initie le flow Authorization Code https://datatracker.ietf.org/doc/html/rfc6749#section-4.1
31
+ */
32
+ async getAuthorizationCode(custom) {
33
+ const options = { ...this.options, ...custom };
34
+ const fn = axios_oauth_client_1.default.authorizationCode(axios_1.default.create(), OAuth2.ACCESS_TOKEN_URL, options.client_id ?? '', options.client_secret ?? '', options.redirect_uri ?? "", options.code ?? "", options.scope ?? "");
35
+ return await fn(options.code ?? "", options.scope ?? "");
36
+ }
37
+ /**
38
+ * Initie le flow Client Credentials https://datatracker.ietf.org/doc/html/rfc6749#section-4.4
39
+ */
40
+ async getClientCredentials(custom) {
41
+ const options = { ...this.options, ...custom };
42
+ const fn = axios_oauth_client_1.default.clientCredentials(axios_1.default.create(), OAuth2.ACCESS_TOKEN_URL, options.client_id ?? '', options.client_secret ?? '');
43
+ return await fn(options.scope ?? "");
44
+ }
45
+ /**
46
+ * Refresh Token (https://datatracker.ietf.org/doc/html/rfc6749#section-1.5)
47
+ */
48
+ async refreshToken(refresh_token, custom) {
49
+ const options = { ...this.options, ...custom };
50
+ const fn = axios_oauth_client_1.default.refreshToken(axios_1.default.create(), OAuth2.ACCESS_TOKEN_URL, options.client_id ?? '', options.client_secret ?? '');
51
+ return await fn(refresh_token);
52
+ }
22
53
  }
23
54
  exports.OAuth2 = OAuth2;
24
- OAuth2.AUTHORIZATION_URL = 'https://lemur-17.cloud-iam.com/auth/realms/metariscoidc/protocol/openid-connect/auth';
25
- OAuth2.ACCESS_TOKEN_URL = 'https://lemur-17.cloud-iam.com/auth/realms/metariscoidc/protocol/openid-connect/token';
55
+ OAuth2.AUTHORIZATION_URL = 'https://id.metarisc.fr/auth/realms/production/protocol/openid-connect/auth';
56
+ OAuth2.ACCESS_TOKEN_URL = 'https://id.metarisc.fr/auth/realms/production/protocol/openid-connect/token';
package/lib/client.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { AxiosResponse } from "axios";
2
- import { GrantResponse, MetariscConfig, OAuth2Options } from './core';
2
+ import { MetariscConfig, OAuth2Options } from "./core";
3
+ import { GrantResponse } from "./auth/oauth2";
3
4
  interface RequestConfig {
4
5
  body?: any;
5
6
  headers?: {
@@ -17,14 +18,31 @@ export declare enum AuthMethod {
17
18
  }
18
19
  export declare class Client {
19
20
  private axios;
20
- private access_token;
21
+ private oauth2;
22
+ private access_token?;
23
+ private refresh_token?;
21
24
  constructor(config: MetariscConfig);
22
25
  authenticate(auth_method: AuthMethod, options: OAuth2Options): Promise<GrantResponse>;
26
+ /**
27
+ * Lance une requête (authentifiée si possible) sur l'API Metarisc.
28
+ */
23
29
  request<T>(config: RequestConfig): Promise<AxiosResponse<T>>;
24
- getAuthorizationCode(options: OAuth2Options): Promise<GrantResponse>;
25
- getClientCredentials(options: OAuth2Options): Promise<GrantResponse>;
30
+ /**
31
+ * Définition de l'Access Token
32
+ */
26
33
  setAccessToken(access_token: string): void;
27
- getAccessToken(): string;
34
+ /**
35
+ * Récupération de l'Access Token
36
+ */
37
+ getAccessToken(): string | undefined;
38
+ /**
39
+ * Définition du Refresh Token
40
+ */
41
+ setRefreshToken(refresh_token: string): void;
42
+ /**
43
+ * Récupération du Refresh Token
44
+ */
45
+ getRefreshToken(): string | undefined;
28
46
  /**
29
47
  * Retourne les headers HTTP par défauts devant être présents dans toutes les requêtes Metarisc.
30
48
  */
package/lib/client.js CHANGED
@@ -6,9 +6,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.Client = exports.AuthMethod = void 0;
7
7
  const axios_1 = __importDefault(require("axios"));
8
8
  const axios_retry_1 = __importDefault(require("axios-retry"));
9
- const axios_oauth_client_1 = __importDefault(require("axios-oauth-client"));
10
9
  const oauth2_1 = require("./auth/oauth2");
11
10
  const axios_cache_interceptor_1 = require("axios-cache-interceptor");
11
+ const utils_1 = __importDefault(require("./utils"));
12
12
  var AuthMethod;
13
13
  (function (AuthMethod) {
14
14
  AuthMethod[AuthMethod["CLIENT_CREDENTIALS"] = 0] = "CLIENT_CREDENTIALS";
@@ -16,11 +16,17 @@ var AuthMethod;
16
16
  })(AuthMethod = exports.AuthMethod || (exports.AuthMethod = {}));
17
17
  class Client {
18
18
  constructor(config) {
19
+ // Paramétrage OAuth2
20
+ this.oauth2 = new oauth2_1.OAuth2({
21
+ client_id: config.client_id,
22
+ client_secret: config.client_secret,
23
+ });
24
+ // Initialisation du client HTTP
19
25
  this.axios = axios_1.default.create({
20
- baseURL: config.metarisc_url ?? 'https://api.metarisc.fr/',
21
- 'headers': {
22
- 'common': this.getDefaultHeaders()
23
- }
26
+ baseURL: config.metarisc_url ?? "https://api.metarisc.fr/",
27
+ headers: {
28
+ common: this.getDefaultHeaders(),
29
+ },
24
30
  });
25
31
  // Axios Interceptors
26
32
  // Request interceptors are FILO (First In Last Out)
@@ -29,67 +35,99 @@ class Client {
29
35
  // When combining axios-cache-interceptors with other interceptors, you may encounter some inconsistences.
30
36
  // See : https://github.com/arthurfiorette/axios-cache-interceptor/issues/449#issuecomment-1370327566
31
37
  this.axios = (0, axios_cache_interceptor_1.setupCache)(this.axios);
38
+ // Axios interceptor : Ajoute l'access token à la requête
39
+ // L'access token peut venir d'un premier authenticate, ou d'un refresh token obtenu au cours des interceptors
40
+ this.axios.interceptors.request.use((config) => {
41
+ config.headers["Authorization"] = this.getAccessToken();
42
+ return config;
43
+ });
32
44
  // Axios interceptor : Retry strategy
33
45
  (0, axios_retry_1.default)(this.axios, {
34
46
  retries: 3,
35
- retryDelay: axios_retry_1.default.exponentialDelay
47
+ retryDelay: axios_retry_1.default.exponentialDelay,
48
+ });
49
+ // Axios interceptor : Refresh Token (https://datatracker.ietf.org/doc/html/rfc6749#section-1.5)
50
+ this.axios.interceptors.request.use(async (config) => {
51
+ // Si l'access_token a expiré on demande un échange avec le refresh token obtenu précedemment
52
+ // Si le refresh ne fonctionne pas, on ne fait rien
53
+ if (this.getAccessToken() !== undefined && this.getRefreshToken() !== undefined && utils_1.default.tokenExpired(this.getAccessToken())) {
54
+ try {
55
+ const result = await this.oauth2.refreshToken(this.getRefreshToken());
56
+ this.setAccessToken(result.token_type + ' ' + result.access_token);
57
+ this.setRefreshToken(result.refresh_token);
58
+ }
59
+ catch (e) {
60
+ //
61
+ }
62
+ }
63
+ return config;
36
64
  });
37
65
  }
38
66
  async authenticate(auth_method, options) {
39
- let result;
40
- switch (auth_method) {
41
- case AuthMethod.AUTHORIZATION_CODE:
42
- result = await this.getAuthorizationCode(options);
43
- break;
44
- case AuthMethod.CLIENT_CREDENTIALS:
45
- result = await this.getClientCredentials(options);
46
- break;
47
- default:
48
- return;
67
+ if (auth_method === AuthMethod.AUTHORIZATION_CODE) {
68
+ const response = await this.oauth2.getAuthorizationCode(options);
69
+ this.setAccessToken(response.token_type + " " + response.access_token);
70
+ this.setRefreshToken(response.refresh_token);
71
+ return response;
49
72
  }
50
- if (result) {
51
- const token = result.token_type + ' ' + result.access_token;
52
- this.setAccessToken(token);
73
+ else if (auth_method === AuthMethod.CLIENT_CREDENTIALS) {
74
+ const response = await this.oauth2.getClientCredentials(options);
75
+ this.setAccessToken(response.token_type + " " + response.access_token);
76
+ return response;
77
+ }
78
+ else {
79
+ throw new Error("auth_method inconnue");
53
80
  }
54
- return result;
55
81
  }
82
+ /**
83
+ * Lance une requête (authentifiée si possible) sur l'API Metarisc.
84
+ */
56
85
  async request(config) {
57
- config.headers['Authorization'] = this.getAccessToken();
58
86
  return this.axios.request({
59
- method: config.method || 'GET',
60
- url: config.endpoint || '/',
87
+ method: config.method || "GET",
88
+ url: config.endpoint || "/",
61
89
  params: config.params,
62
90
  data: config.body,
63
- headers: config.headers
91
+ headers: config.headers,
64
92
  });
65
93
  }
66
- async getAuthorizationCode(options) {
67
- const fn = axios_oauth_client_1.default.authorizationCode(axios_1.default.create(), oauth2_1.OAuth2.ACCESS_TOKEN_URL, options.client_id ?? '', options.client_secret ?? '', options.redirect_uri ?? '', options.code ?? '', options.scope ?? '');
68
- return await fn(options.code ?? '', options.scope ?? '');
69
- }
70
- async getClientCredentials(options) {
71
- const fn = axios_oauth_client_1.default.clientCredentials(axios_1.default.create(), oauth2_1.OAuth2.ACCESS_TOKEN_URL, options.client_id ?? '', options.client_secret ?? '');
72
- return await fn(options.scope ?? '');
73
- }
94
+ /**
95
+ * Définition de l'Access Token
96
+ */
74
97
  setAccessToken(access_token) {
75
98
  this.access_token = access_token;
76
- this.axios.interceptors.request.use(function (config) {
77
- config.headers['Authorization'] = access_token;
78
- return config;
79
- });
80
99
  }
100
+ /**
101
+ * Récupération de l'Access Token
102
+ */
81
103
  getAccessToken() {
82
104
  return this.access_token;
83
105
  }
106
+ /**
107
+ * Définition du Refresh Token
108
+ */
109
+ setRefreshToken(refresh_token) {
110
+ this.refresh_token = refresh_token;
111
+ }
112
+ /**
113
+ * Récupération du Refresh Token
114
+ */
115
+ getRefreshToken() {
116
+ return this.refresh_token;
117
+ }
84
118
  /**
85
119
  * Retourne les headers HTTP par défauts devant être présents dans toutes les requêtes Metarisc.
86
120
  */
87
121
  getDefaultHeaders() {
122
+ const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; // https://github.com/axios/axios/blob/v1.x/lib/platform/common/utils.js#L1
88
123
  const headers = {};
89
- // UA Headers
90
- headers['User-Agent'] = 'MetariscJs/dev'; // Format User-Agent (https://www.rfc-editor.org/rfc/rfc9110#name-user-agent)
91
- headers['Metarisc-User-Agent'] = JSON.stringify({
92
- 'lang': 'js'
124
+ // UA Headers (surcharge le UA uniquement sur un env Server car le navigateur considéra cela comme unsafe)
125
+ if (!hasBrowserEnv) {
126
+ headers["User-Agent"] = "MetariscJs/dev"; // Format User-Agent (https://www.rfc-editor.org/rfc/rfc9110#name-user-agent)
127
+ }
128
+ headers["Metarisc-User-Agent"] = JSON.stringify({
129
+ lang: "js",
130
+ version: 'dev'
93
131
  });
94
132
  return headers;
95
133
  }
package/lib/core.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { AxiosResponse } from "axios";
2
2
  import { AuthMethod, Client } from "./client";
3
3
  import { Collection } from "./collection";
4
+ import { GrantResponse } from "./auth/oauth2";
4
5
  interface RequestConfig {
5
6
  body?: any;
6
7
  headers?: {
@@ -14,10 +15,10 @@ interface RequestConfig {
14
15
  }
15
16
  export interface MetariscConfig {
16
17
  metarisc_url?: string;
18
+ client_id: string;
19
+ client_secret?: string;
17
20
  }
18
21
  export interface OAuth2Options {
19
- client_id?: string;
20
- client_secret?: string;
21
22
  response_type?: string;
22
23
  redirect_uri?: string;
23
24
  state?: string;
@@ -25,17 +26,6 @@ export interface OAuth2Options {
25
26
  scope?: string;
26
27
  [name: string]: string;
27
28
  }
28
- export interface GrantResponse {
29
- access_token?: string;
30
- expires_in?: number;
31
- id_token?: string;
32
- refresh_token?: string;
33
- refresh_expires_in?: number;
34
- session_state?: string;
35
- token_type?: string;
36
- error?: string;
37
- error_description?: string;
38
- }
39
29
  export declare class Core {
40
30
  protected client: Client;
41
31
  protected config: MetariscConfig;
@@ -44,5 +34,6 @@ export declare class Core {
44
34
  collect<T>(config: RequestConfig): Collection<T>;
45
35
  authenticate(auth_method: AuthMethod, options: OAuth2Options): Promise<GrantResponse>;
46
36
  setAccessToken(access_token: string): void;
37
+ setRefreshToken(refresh_token: string): void;
47
38
  }
48
39
  export {};
package/lib/core.js CHANGED
@@ -13,9 +13,9 @@ class Core {
13
13
  }
14
14
  collect(config) {
15
15
  return new collection_1.Collection(this, {
16
- endpoint: config.endpoint || '/',
16
+ endpoint: config.endpoint || "/",
17
17
  params: config.params,
18
- headers: config.headers
18
+ headers: config.headers,
19
19
  });
20
20
  }
21
21
  async authenticate(auth_method, options) {
@@ -24,5 +24,8 @@ class Core {
24
24
  setAccessToken(access_token) {
25
25
  this.client.setAccessToken(access_token);
26
26
  }
27
+ setRefreshToken(refresh_token) {
28
+ this.client.setRefreshToken(refresh_token);
29
+ }
27
30
  }
28
31
  exports.Core = Core;
package/lib/index.d.ts CHANGED
@@ -1,16 +1,16 @@
1
1
  export { Metarisc } from "./metarisc";
2
2
  export { OAuth2 } from "./auth/oauth2";
3
3
  export { Core } from "./core";
4
- export { Collection } from "./collection";
5
- export { PaginationResults, PaginationData } from "./collection";
6
- export { AuthMethod } from "./client";
7
- export { Client } from "./client";
4
+ export { Collection, PaginationData, PaginationResults } from "./collection";
5
+ export { AuthMethod, Client } from "./client";
8
6
  export { Tus } from "./tus";
9
7
  export { DossiersAPI } from './api/DossiersAPI';
10
8
  export { EvenementsAPI } from './api/EvenementsAPI';
11
9
  export { FeedAPI } from './api/FeedAPI';
10
+ export { MoiAPI } from './api/MoiAPI';
12
11
  export { NotificationsAPI } from './api/NotificationsAPI';
13
12
  export { OrganisationsAPI } from './api/OrganisationsAPI';
14
13
  export { PEIAPI } from './api/PEIAPI';
15
14
  export { PingAPI } from './api/PingAPI';
15
+ export { SupportAPI } from './api/SupportAPI';
16
16
  export { UtilisateursAPI } from './api/UtilisateursAPI';