rest-client-sdk 7.2.0 → 7.2.1
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/dist/{index.js → index.cjs} +1 -1
- package/dist/index.cjs.map +1 -0
- package/dist/{index.es.js → index.mjs} +1 -1
- package/dist/index.mjs.map +1 -0
- package/package.json +10 -14
- package/dist/index.es.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/src/AsyncStorageInterface.ts +0 -7
- package/src/ErrorFactory.ts +0 -258
- package/src/Mapping/Attribute.ts +0 -33
- package/src/Mapping/ClassMetadata.ts +0 -125
- package/src/Mapping/Relation.ts +0 -68
- package/src/Mapping.ts +0 -120
- package/src/RestClientSdk.ts +0 -127
- package/src/RestClientSdkInterface.ts +0 -27
- package/src/TokenGenerator/AbstractTokenGenerator.ts +0 -86
- package/src/TokenGenerator/AuthorizationCodeFlowTokenGenerator.ts +0 -146
- package/src/TokenGenerator/ClientCredentialsGenerator.ts +0 -97
- package/src/TokenGenerator/PasswordGenerator.ts +0 -140
- package/src/TokenGenerator/ProvidedTokenGenerator.ts +0 -44
- package/src/TokenGenerator/TokenGeneratorInterface.ts +0 -27
- package/src/TokenGenerator/types.ts +0 -33
- package/src/TokenStorage.ts +0 -256
- package/src/TokenStorageInterface.ts +0 -14
- package/src/UnitOfWork.ts +0 -354
- package/src/client/AbstractClient.ts +0 -545
- package/src/client/headerUtils.ts +0 -53
- package/src/decorator.ts +0 -53
- package/src/index.ts +0 -86
- package/src/isImmutable.ts +0 -52
- package/src/serializer/JsSerializer.ts +0 -30
- package/src/serializer/Serializer.ts +0 -138
- package/src/serializer/SerializerInterface.ts +0 -89
- package/src/utils/levenshtein.ts +0 -53
- package/src/utils/logging.ts +0 -96
- package/src/utils/repositoryGenerator.ts +0 -16
|
@@ -1,125 +0,0 @@
|
|
|
1
|
-
import AbstractClient from '../client/AbstractClient';
|
|
2
|
-
import Attribute from './Attribute';
|
|
3
|
-
import Relation from './Relation';
|
|
4
|
-
|
|
5
|
-
type AttributeListType = { [key: string]: Attribute };
|
|
6
|
-
type RelationListType = { [key: string]: Relation };
|
|
7
|
-
export type DefaultSerializedModelType = {
|
|
8
|
-
[key: string]: null | null[];
|
|
9
|
-
};
|
|
10
|
-
|
|
11
|
-
class ClassMetadata {
|
|
12
|
-
readonly key: string;
|
|
13
|
-
|
|
14
|
-
readonly pathRoot: string;
|
|
15
|
-
|
|
16
|
-
repositoryClass: typeof AbstractClient;
|
|
17
|
-
|
|
18
|
-
#attributeList: AttributeListType;
|
|
19
|
-
|
|
20
|
-
#relationList: RelationListType;
|
|
21
|
-
|
|
22
|
-
#identifierAttribute?: Attribute;
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* @param {string} key mandatory, will be passed in your serializer
|
|
26
|
-
* @param {string|null} pathRoot the endpoint of your API: will be added to the mapping prefix ('/v1' here)
|
|
27
|
-
* @param {typeof AbstractClient} repositoryClass [Overriding repository]{@link https://github.com/mapado/rest-client-js-sdk#overriding-repository} for more detail
|
|
28
|
-
*/
|
|
29
|
-
constructor(
|
|
30
|
-
key: string,
|
|
31
|
-
pathRoot: string | null = null,
|
|
32
|
-
// modelName,
|
|
33
|
-
repositoryClass: typeof AbstractClient = AbstractClient
|
|
34
|
-
) {
|
|
35
|
-
if (!key) {
|
|
36
|
-
throw new TypeError('key attribute are required');
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
this.key = key;
|
|
40
|
-
this.pathRoot = pathRoot || key;
|
|
41
|
-
// this.modelName = modelName;
|
|
42
|
-
this.repositoryClass = repositoryClass;
|
|
43
|
-
|
|
44
|
-
this.#attributeList = {};
|
|
45
|
-
this.#relationList = {};
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
getAttribute(name: string): Attribute {
|
|
49
|
-
return this.#attributeList[name];
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
hasIdentifierAttribute(): boolean {
|
|
53
|
-
return !!this.#identifierAttribute;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
getIdentifierAttribute(): Attribute {
|
|
57
|
-
if (!this.#identifierAttribute) {
|
|
58
|
-
throw new TypeError(
|
|
59
|
-
`"${this.key}" has no identifier attribute set. Did you call "setAttributeList" first ?`
|
|
60
|
-
);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
return this.#identifierAttribute;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
getAttributeList(): AttributeListType {
|
|
67
|
-
return this.#attributeList;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
setAttributeList(attributeList: Attribute[]): void {
|
|
71
|
-
this.#attributeList = {};
|
|
72
|
-
this.#identifierAttribute = undefined;
|
|
73
|
-
|
|
74
|
-
attributeList.forEach((attribute) => {
|
|
75
|
-
this.#attributeList[attribute.serializedKey] = attribute;
|
|
76
|
-
|
|
77
|
-
if (attribute.isIdentifier) {
|
|
78
|
-
this.#identifierAttribute = attribute;
|
|
79
|
-
}
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
if (!this.#identifierAttribute) {
|
|
83
|
-
throw new TypeError(
|
|
84
|
-
`"${this.key}" has no identifier attribute set. You must set all your attributes in one time and send an attribute with "isIdentifier=true"`
|
|
85
|
-
);
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
setRelationList(relationList: Relation[]): void {
|
|
90
|
-
this.#relationList = {};
|
|
91
|
-
|
|
92
|
-
relationList.forEach((relation) => {
|
|
93
|
-
this.#relationList[relation.serializedKey] = relation;
|
|
94
|
-
this.#attributeList[relation.serializedKey] = new Attribute(
|
|
95
|
-
relation.serializedKey,
|
|
96
|
-
relation.serializedKey,
|
|
97
|
-
relation.isRelationToMany() ? 'array' : 'object'
|
|
98
|
-
);
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
getRelation(key: string): Relation {
|
|
103
|
-
return this.#relationList[key];
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
getDefaultSerializedModel(): DefaultSerializedModelType {
|
|
107
|
-
const out: DefaultSerializedModelType = {};
|
|
108
|
-
|
|
109
|
-
Object.keys(this.#attributeList).forEach((serializedKey) => {
|
|
110
|
-
out[serializedKey] = null;
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
Object.keys(this.#relationList).forEach((serializedKey) => {
|
|
114
|
-
const relation = this.#relationList[serializedKey];
|
|
115
|
-
|
|
116
|
-
if (relation.isRelationToMany()) {
|
|
117
|
-
out[serializedKey] = [];
|
|
118
|
-
}
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
return out;
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
export default ClassMetadata;
|
package/src/Mapping/Relation.ts
DELETED
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
enum RelationTypes {
|
|
2
|
-
ONE_TO_ONE = 'ONE_TO_ONE',
|
|
3
|
-
ONE_TO_MANY = 'ONE_TO_MANY',
|
|
4
|
-
MANY_TO_MANY = 'MANY_TO_MANY',
|
|
5
|
-
MANY_TO_ONE = 'MANY_TO_ONE',
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
class Relation {
|
|
9
|
-
public static ONE_TO_ONE = RelationTypes.ONE_TO_ONE;
|
|
10
|
-
|
|
11
|
-
public static ONE_TO_MANY = RelationTypes.ONE_TO_MANY;
|
|
12
|
-
|
|
13
|
-
public static MANY_TO_ONE = RelationTypes.MANY_TO_ONE;
|
|
14
|
-
|
|
15
|
-
public static MANY_TO_MANY = RelationTypes.MANY_TO_MANY;
|
|
16
|
-
|
|
17
|
-
type: RelationTypes;
|
|
18
|
-
|
|
19
|
-
readonly targetMetadataKey: string;
|
|
20
|
-
|
|
21
|
-
readonly serializedKey: string;
|
|
22
|
-
|
|
23
|
-
readonly attributeName: string;
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* @param {RelationTypes} type the type of relation
|
|
27
|
-
* @param {string} targetMetadataKey must match the first argument of `ClassMetadata` constructor of the target entity
|
|
28
|
-
* @param {string} serializedKey the key returned from your API
|
|
29
|
-
* @param {string|null} attributeName the name in your entity, default to the `serializedKey` attribute
|
|
30
|
-
*/
|
|
31
|
-
constructor(
|
|
32
|
-
type: RelationTypes,
|
|
33
|
-
targetMetadataKey: string,
|
|
34
|
-
serializedKey: string,
|
|
35
|
-
attributeName: string | null = null
|
|
36
|
-
) {
|
|
37
|
-
this.type = type;
|
|
38
|
-
this.targetMetadataKey = targetMetadataKey;
|
|
39
|
-
this.serializedKey = serializedKey;
|
|
40
|
-
this.attributeName = attributeName || this.serializedKey;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
isOneToOne(): boolean {
|
|
44
|
-
return this.type === Relation.ONE_TO_ONE;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
isOneToMany(): boolean {
|
|
48
|
-
return this.type === Relation.ONE_TO_MANY;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
isManyToOne(): boolean {
|
|
52
|
-
return this.type === Relation.MANY_TO_ONE;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
isManyToMany(): boolean {
|
|
56
|
-
return this.type === Relation.MANY_TO_MANY;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
isRelationToMany(): boolean {
|
|
60
|
-
return this.isManyToMany() || this.isOneToMany();
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
isRelationToOne(): boolean {
|
|
64
|
-
return this.isManyToOne() || this.isOneToOne();
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export default Relation;
|
package/src/Mapping.ts
DELETED
|
@@ -1,120 +0,0 @@
|
|
|
1
|
-
import ClassMetadata from './Mapping/ClassMetadata';
|
|
2
|
-
|
|
3
|
-
const DEFAULT_CONFIG = {
|
|
4
|
-
collectionKey: 'hydra:member',
|
|
5
|
-
};
|
|
6
|
-
|
|
7
|
-
class Mapping {
|
|
8
|
-
readonly idPrefix: string;
|
|
9
|
-
|
|
10
|
-
#config!: Record<string, unknown>;
|
|
11
|
-
|
|
12
|
-
#classMetadataList: ClassMetadata[];
|
|
13
|
-
|
|
14
|
-
constructor(idPrefix = '', config = {}) {
|
|
15
|
-
this.idPrefix = idPrefix;
|
|
16
|
-
|
|
17
|
-
this.#classMetadataList = [];
|
|
18
|
-
|
|
19
|
-
this.setConfig(config);
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
getConfig(): Record<string, unknown> {
|
|
23
|
-
return this.#config;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
setConfig(config: Record<string, unknown>): void {
|
|
27
|
-
this.#config = { ...DEFAULT_CONFIG, ...config };
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
setMapping(classMetadataList: ClassMetadata[] = []): void {
|
|
31
|
-
this.#classMetadataList = classMetadataList;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
getMappingKeys(): string[] {
|
|
35
|
-
return this.#classMetadataList.map((classMetadata) => classMetadata.key);
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
getClassMetadataByKey(key: string): null | ClassMetadata {
|
|
39
|
-
const filterList = this.#classMetadataList.filter(
|
|
40
|
-
(classMetadata) => classMetadata.key === key
|
|
41
|
-
);
|
|
42
|
-
|
|
43
|
-
return filterList.length > 0 ? filterList[0] : null;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
isMappingValid(): boolean {
|
|
47
|
-
return !this.#classMetadataList.some((classMetadata) => {
|
|
48
|
-
// check that the relations exists
|
|
49
|
-
const errorList = Object.values(classMetadata.getAttributeList()).map(
|
|
50
|
-
(attribute) => {
|
|
51
|
-
const relation = classMetadata.getRelation(attribute.serializedKey);
|
|
52
|
-
|
|
53
|
-
if (!relation) {
|
|
54
|
-
// attribute can not be "invalid" (for now ?)
|
|
55
|
-
return false;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
const relationMetadata = this.getClassMetadataByKey(
|
|
59
|
-
relation.targetMetadataKey
|
|
60
|
-
);
|
|
61
|
-
|
|
62
|
-
// relation name seems weird
|
|
63
|
-
if (
|
|
64
|
-
relation.isRelationToOne() &&
|
|
65
|
-
attribute.attributeName.endsWith('List')
|
|
66
|
-
) {
|
|
67
|
-
return `"${classMetadata.key}.${attribute.serializedKey} is defined as a MANY_TO_ONE relation, but the attribute name ends with "List".`;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
if (relation.isRelationToMany()) {
|
|
71
|
-
const message = `"${classMetadata.key}.${attribute.serializedKey} is defined as a ${relation.type} relation, but the attribute name is nor plural not ends with "List".`;
|
|
72
|
-
|
|
73
|
-
const endsWithList = attribute.attributeName.endsWith('List');
|
|
74
|
-
|
|
75
|
-
try {
|
|
76
|
-
// eslint-disable-next-line global-require, import/no-extraneous-dependencies, @typescript-eslint/no-var-requires
|
|
77
|
-
const pluralize = require('pluralize');
|
|
78
|
-
if (
|
|
79
|
-
!endsWithList &&
|
|
80
|
-
!pluralize.isPlural(attribute.attributeName)
|
|
81
|
-
) {
|
|
82
|
-
return message;
|
|
83
|
-
}
|
|
84
|
-
} catch (e) {
|
|
85
|
-
if (!endsWithList) {
|
|
86
|
-
return `${message}.\nIf your keys does not ends with "List", then you should install the "pluralize" package.`;
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
// no error if there is metadata linked
|
|
92
|
-
if (!relationMetadata) {
|
|
93
|
-
return `"${classMetadata.key}.${attribute.serializedKey}" defined a relation to the metadata named "${relation.targetMetadataKey}" but this metadata is not knowned by the mapping`;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
return false;
|
|
97
|
-
}
|
|
98
|
-
);
|
|
99
|
-
|
|
100
|
-
if (!classMetadata.hasIdentifierAttribute()) {
|
|
101
|
-
errorList.push(
|
|
102
|
-
`"${classMetadata.key}" has no identifier attribute set`
|
|
103
|
-
);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
const nbError = errorList.filter((error) => {
|
|
107
|
-
if (error) {
|
|
108
|
-
// eslint-disable-next-line no-console
|
|
109
|
-
console.warn(error);
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
return error;
|
|
113
|
-
});
|
|
114
|
-
|
|
115
|
-
return nbError.length > 0;
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
export default Mapping;
|
package/src/RestClientSdk.ts
DELETED
|
@@ -1,127 +0,0 @@
|
|
|
1
|
-
import Mapping from './Mapping';
|
|
2
|
-
// eslint-disable-next-line import/no-duplicates
|
|
3
|
-
import type RestClientSdkInterface from './RestClientSdkInterface';
|
|
4
|
-
// eslint-disable-next-line import/no-duplicates
|
|
5
|
-
import type { Config } from './RestClientSdkInterface';
|
|
6
|
-
import { Token } from './TokenGenerator/types';
|
|
7
|
-
import TokenStorageInterface from './TokenStorageInterface';
|
|
8
|
-
import UnitOfWork from './UnitOfWork';
|
|
9
|
-
import AbstractClient from './client/AbstractClient';
|
|
10
|
-
import JsSerializer from './serializer/JsSerializer';
|
|
11
|
-
import SerializerInterface from './serializer/SerializerInterface';
|
|
12
|
-
import { findClosestWord } from './utils/levenshtein';
|
|
13
|
-
import { Logger } from './utils/logging';
|
|
14
|
-
import { generateRepository } from './utils/repositoryGenerator';
|
|
15
|
-
|
|
16
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
17
|
-
type Entity = any;
|
|
18
|
-
|
|
19
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
20
|
-
// export type SdkMetadata = Record<string, [any, Iterable<any>, undefined | any]>;
|
|
21
|
-
export type MetadataDefinition = {
|
|
22
|
-
entity: Entity;
|
|
23
|
-
list: Iterable<Entity>;
|
|
24
|
-
// repository?: typeof AbstractClient;
|
|
25
|
-
};
|
|
26
|
-
|
|
27
|
-
export type SdkMetadata = Record<string, MetadataDefinition>;
|
|
28
|
-
|
|
29
|
-
class RestClientSdk<M extends SdkMetadata>
|
|
30
|
-
implements RestClientSdkInterface<M> {
|
|
31
|
-
config: Config;
|
|
32
|
-
|
|
33
|
-
public tokenStorage: TokenStorageInterface<Token>;
|
|
34
|
-
|
|
35
|
-
public serializer: SerializerInterface;
|
|
36
|
-
|
|
37
|
-
public mapping: Mapping;
|
|
38
|
-
|
|
39
|
-
public unitOfWork: UnitOfWork;
|
|
40
|
-
|
|
41
|
-
#repositoryList: Partial<Record<keyof M, AbstractClient<M[keyof M]>>>;
|
|
42
|
-
|
|
43
|
-
public readonly logger?: Logger;
|
|
44
|
-
|
|
45
|
-
constructor(
|
|
46
|
-
tokenStorage: TokenStorageInterface<Token>,
|
|
47
|
-
config: Config,
|
|
48
|
-
mapping: Mapping,
|
|
49
|
-
serializer: SerializerInterface = new JsSerializer()
|
|
50
|
-
) {
|
|
51
|
-
this.checkConfigValidity(config);
|
|
52
|
-
|
|
53
|
-
if (!(mapping instanceof Mapping)) {
|
|
54
|
-
throw new TypeError('mapping should be an instance of `Mapping`');
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
this.config = this._mergeWithBaseConfig(config);
|
|
58
|
-
this.tokenStorage = tokenStorage;
|
|
59
|
-
this.serializer = serializer;
|
|
60
|
-
this.mapping = mapping;
|
|
61
|
-
|
|
62
|
-
this.unitOfWork = new UnitOfWork(
|
|
63
|
-
this.mapping,
|
|
64
|
-
this.config.unitOfWorkEnabled
|
|
65
|
-
);
|
|
66
|
-
|
|
67
|
-
if (config.loggerEnabled) {
|
|
68
|
-
this.logger = new Logger();
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
this.#repositoryList = {};
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* get a repository by it's metadata "key" attribute
|
|
76
|
-
*
|
|
77
|
-
* @param {string} key the repository "key" (the first argument of `new ClassMetadata`)
|
|
78
|
-
*/
|
|
79
|
-
getRepository<K extends keyof M & string>(key: K): AbstractClient<M[K]> {
|
|
80
|
-
if (!this.#repositoryList[key]) {
|
|
81
|
-
const metadata = this.mapping.getClassMetadataByKey(key);
|
|
82
|
-
|
|
83
|
-
if (!metadata) {
|
|
84
|
-
const closeKey = findClosestWord(key, this.mapping.getMappingKeys(), 5);
|
|
85
|
-
|
|
86
|
-
const suggestions = closeKey ? ` Did you mean "${closeKey}"?` : '';
|
|
87
|
-
|
|
88
|
-
throw new Error(
|
|
89
|
-
`Unable to get metadata for repository "${key}".${suggestions}`
|
|
90
|
-
);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
// eslint-disable-next-line new-cap
|
|
94
|
-
this.#repositoryList[key] = generateRepository<M[K]>(
|
|
95
|
-
this,
|
|
96
|
-
metadata,
|
|
97
|
-
this.config.unitOfWorkEnabled
|
|
98
|
-
);
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
102
|
-
return (this.#repositoryList[key]! as unknown) as AbstractClient<M[K]>;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
private _mergeWithBaseConfig(config: Config): Config {
|
|
106
|
-
const newConfig = config;
|
|
107
|
-
newConfig.useDefaultParameters =
|
|
108
|
-
config.useDefaultParameters === undefined
|
|
109
|
-
? true
|
|
110
|
-
: config.useDefaultParameters;
|
|
111
|
-
|
|
112
|
-
newConfig.authorizationType = config.authorizationType || 'Bearer';
|
|
113
|
-
|
|
114
|
-
return newConfig;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
private checkConfigValidity(config: Config): void {
|
|
118
|
-
if (!(config && config.path && config.scheme)) {
|
|
119
|
-
throw new RangeError(
|
|
120
|
-
`SDK config is not valid, it should contain a "path", a "scheme" parameter,
|
|
121
|
-
and may contain a "port" and a "useDefaultParameters" parameter`
|
|
122
|
-
);
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
export default RestClientSdk;
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import Mapping from './Mapping';
|
|
2
|
-
import { SdkMetadata } from './RestClientSdk';
|
|
3
|
-
import { Token } from './TokenGenerator/types';
|
|
4
|
-
import TokenStorageInterface from './TokenStorageInterface';
|
|
5
|
-
import AbstractClient from './client/AbstractClient';
|
|
6
|
-
import { Logger } from './utils/logging';
|
|
7
|
-
|
|
8
|
-
export type Config = {
|
|
9
|
-
path: string;
|
|
10
|
-
scheme: string;
|
|
11
|
-
port?: number;
|
|
12
|
-
segment?: string;
|
|
13
|
-
authorizationType?: string; // default to "Bearer", but can be "Basic" or anything
|
|
14
|
-
useDefaultParameters?: boolean;
|
|
15
|
-
unitOfWorkEnabled?: boolean;
|
|
16
|
-
loggerEnabled?: boolean;
|
|
17
|
-
onRefreshTokenFailure?: (error: Error) => void;
|
|
18
|
-
};
|
|
19
|
-
|
|
20
|
-
export default interface RestClientSdkInterface<M extends SdkMetadata> {
|
|
21
|
-
tokenStorage: TokenStorageInterface<Token>;
|
|
22
|
-
mapping: Mapping;
|
|
23
|
-
|
|
24
|
-
readonly logger?: Logger;
|
|
25
|
-
|
|
26
|
-
getRepository<K extends keyof M & string>(key: K): AbstractClient<M[K]>;
|
|
27
|
-
}
|
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
/* eslint no-unused-vars: 0 */
|
|
2
|
-
import URI from 'urijs';
|
|
3
|
-
import {
|
|
4
|
-
getHttpErrorFromResponse,
|
|
5
|
-
InvalidGrantError,
|
|
6
|
-
InvalidScopeError,
|
|
7
|
-
OauthError,
|
|
8
|
-
} from '../ErrorFactory';
|
|
9
|
-
import { Logger } from '../utils/logging';
|
|
10
|
-
import TokenGeneratorInterface, {
|
|
11
|
-
TokenBodyReturn,
|
|
12
|
-
} from './TokenGeneratorInterface';
|
|
13
|
-
import { ErrorBody, Token, TokenResponse } from './types';
|
|
14
|
-
|
|
15
|
-
interface UrlConfig {
|
|
16
|
-
scheme: string;
|
|
17
|
-
path: string;
|
|
18
|
-
port?: string;
|
|
19
|
-
}
|
|
20
|
-
abstract class AbstractTokenGenerator<T extends Token, C>
|
|
21
|
-
implements TokenGeneratorInterface<T> {
|
|
22
|
-
readonly tokenGeneratorConfig: C;
|
|
23
|
-
|
|
24
|
-
protected logger?: Logger;
|
|
25
|
-
|
|
26
|
-
constructor(tokenGeneratorConfig: C, logger?: Logger) {
|
|
27
|
-
if (logger) {
|
|
28
|
-
this.logger = logger;
|
|
29
|
-
}
|
|
30
|
-
this.tokenGeneratorConfig = tokenGeneratorConfig;
|
|
31
|
-
if (typeof this.checkTokenGeneratorConfig === 'function') {
|
|
32
|
-
this.checkTokenGeneratorConfig(this.tokenGeneratorConfig);
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
abstract generateToken(
|
|
37
|
-
parameters: unknown
|
|
38
|
-
): Promise<TokenBodyReturn<T> | TokenResponse<T>>;
|
|
39
|
-
|
|
40
|
-
abstract refreshToken(
|
|
41
|
-
accessToken: null | T
|
|
42
|
-
): Promise<TokenBodyReturn<T> | TokenResponse<T>>;
|
|
43
|
-
|
|
44
|
-
abstract checkTokenGeneratorConfig(config: C): void;
|
|
45
|
-
|
|
46
|
-
/** @deprecated */
|
|
47
|
-
protected _manageOauthError(response: Response): Promise<never> {
|
|
48
|
-
return response
|
|
49
|
-
.clone()
|
|
50
|
-
.json()
|
|
51
|
-
.then((body: ErrorBody) => {
|
|
52
|
-
if (body.error === 'invalid_grant') {
|
|
53
|
-
throw new InvalidGrantError(
|
|
54
|
-
body.error,
|
|
55
|
-
getHttpErrorFromResponse(response)
|
|
56
|
-
);
|
|
57
|
-
}
|
|
58
|
-
if (body.error === 'invalid_scope') {
|
|
59
|
-
throw new InvalidScopeError(
|
|
60
|
-
body.error,
|
|
61
|
-
getHttpErrorFromResponse(response)
|
|
62
|
-
);
|
|
63
|
-
}
|
|
64
|
-
throw new OauthError(body.error, getHttpErrorFromResponse(response));
|
|
65
|
-
})
|
|
66
|
-
.catch((err) => {
|
|
67
|
-
if (!(err instanceof OauthError)) {
|
|
68
|
-
throw new OauthError(err.type, getHttpErrorFromResponse(response));
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
throw err;
|
|
72
|
-
});
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
protected generateUrlFromConfig(config: UrlConfig): string {
|
|
76
|
-
const uri = new URI(`${config.scheme}://${config.path}`);
|
|
77
|
-
|
|
78
|
-
if (config.port) {
|
|
79
|
-
uri.port(config.port);
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
return uri.toString();
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
export default AbstractTokenGenerator;
|
|
@@ -1,146 +0,0 @@
|
|
|
1
|
-
/* eslint-disable camelcase */
|
|
2
|
-
import AbstractTokenGenerator from './AbstractTokenGenerator';
|
|
3
|
-
import { Token, TokenResponse } from './types';
|
|
4
|
-
|
|
5
|
-
type AuthorizationCodeFlowTokenGeneratorConfig = {
|
|
6
|
-
clientId: string;
|
|
7
|
-
clientSecret: string;
|
|
8
|
-
path: string;
|
|
9
|
-
scheme: string;
|
|
10
|
-
redirectUri: string;
|
|
11
|
-
port?: string;
|
|
12
|
-
scope?: string;
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
type GenerateTokenParameters = {
|
|
16
|
-
code: string;
|
|
17
|
-
state?: string;
|
|
18
|
-
};
|
|
19
|
-
|
|
20
|
-
interface AuthorizationCodeToken extends Token {
|
|
21
|
-
access_token: string;
|
|
22
|
-
token_type: string;
|
|
23
|
-
refresh_token: string;
|
|
24
|
-
expires_in?: number;
|
|
25
|
-
scope?: string;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
type AuthorizationCodeFlowResponse = TokenResponse<AuthorizationCodeToken>;
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* This generator take cares of the second part of the authorization code flow : the part where you have a "code"
|
|
32
|
-
* and you have validated the "state"
|
|
33
|
-
* @See {@link https://oauth2.thephpleague.com/authorization-server/auth-code-grant/|the great article of the PHP League} about authorization code flow.
|
|
34
|
-
*/
|
|
35
|
-
class AuthorizationCodeFlowTokenGenerator extends AbstractTokenGenerator<
|
|
36
|
-
AuthorizationCodeToken,
|
|
37
|
-
AuthorizationCodeFlowTokenGeneratorConfig
|
|
38
|
-
> {
|
|
39
|
-
/**
|
|
40
|
-
* This function needs no generate an access token
|
|
41
|
-
*/
|
|
42
|
-
generateToken(
|
|
43
|
-
parameters: GenerateTokenParameters
|
|
44
|
-
): Promise<AuthorizationCodeFlowResponse> {
|
|
45
|
-
this._checkGenerateParameters(parameters);
|
|
46
|
-
|
|
47
|
-
const url = this.generateUrlFromConfig(this.tokenGeneratorConfig);
|
|
48
|
-
|
|
49
|
-
const params = {
|
|
50
|
-
method: 'POST',
|
|
51
|
-
headers: {
|
|
52
|
-
'Content-Type': 'application/x-www-form-urlencoded',
|
|
53
|
-
},
|
|
54
|
-
body: new URLSearchParams({
|
|
55
|
-
grant_type: 'authorization_code',
|
|
56
|
-
client_id: this.tokenGeneratorConfig.clientId,
|
|
57
|
-
client_secret: this.tokenGeneratorConfig.clientSecret, // TODO : secure this ?
|
|
58
|
-
redirect_uri: this.tokenGeneratorConfig.redirectUri,
|
|
59
|
-
code: parameters.code,
|
|
60
|
-
}).toString(),
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
if (this.logger) {
|
|
64
|
-
this.logger.logRequest({ url, ...params });
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
return fetch(url, params);
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/**
|
|
71
|
-
* This function needs to refresh the current possibly expired access token
|
|
72
|
-
* and return a Promise that will be resolved with a fresh access token
|
|
73
|
-
*/
|
|
74
|
-
refreshToken(
|
|
75
|
-
oldAccessToken: null | AuthorizationCodeToken
|
|
76
|
-
): Promise<AuthorizationCodeFlowResponse> {
|
|
77
|
-
if (!oldAccessToken) {
|
|
78
|
-
throw new Error(
|
|
79
|
-
'refresh_token is not set. Did you called `generateToken` before ?'
|
|
80
|
-
);
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
if (!oldAccessToken?.refresh_token) {
|
|
84
|
-
throw new Error('Unable to refreshToken as there are no refresh_token');
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
const url = this.generateUrlFromConfig(this.tokenGeneratorConfig);
|
|
88
|
-
|
|
89
|
-
const params = {
|
|
90
|
-
method: 'POST',
|
|
91
|
-
headers: {
|
|
92
|
-
'Content-Type': 'application/x-www-form-urlencoded',
|
|
93
|
-
},
|
|
94
|
-
body: new URLSearchParams({
|
|
95
|
-
grant_type: 'refresh_token',
|
|
96
|
-
client_id: this.tokenGeneratorConfig.clientId,
|
|
97
|
-
client_secret: this.tokenGeneratorConfig.clientSecret,
|
|
98
|
-
refresh_token: oldAccessToken.refresh_token,
|
|
99
|
-
}).toString(),
|
|
100
|
-
};
|
|
101
|
-
|
|
102
|
-
if (this.logger) {
|
|
103
|
-
this.logger.logRequest({ url, ...params });
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
return fetch(url, params);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
checkTokenGeneratorConfig(
|
|
110
|
-
config: AuthorizationCodeFlowTokenGeneratorConfig
|
|
111
|
-
): void {
|
|
112
|
-
if (!config || Object.keys(config).length === 0) {
|
|
113
|
-
throw new RangeError('TokenGenerator config must be set');
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
if (!(config.path && config.scheme)) {
|
|
117
|
-
throw new RangeError(
|
|
118
|
-
'TokenGenerator config is not valid, it should contain a "path", a "scheme" parameter'
|
|
119
|
-
);
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
if (!(config.clientId && config.clientSecret)) {
|
|
123
|
-
throw new RangeError(
|
|
124
|
-
'TokenGenerator config is not valid, it should contain a "clientId", a "clientSecret" parameter'
|
|
125
|
-
);
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
if (!config.redirectUri) {
|
|
129
|
-
throw new RangeError(
|
|
130
|
-
'TokenGenerator config is not valid, it should contain a "redirectUri" parameter'
|
|
131
|
-
);
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
private _checkGenerateParameters(parameters: GenerateTokenParameters): void {
|
|
136
|
-
if (!(parameters && Object.keys(parameters).length > 0)) {
|
|
137
|
-
throw new RangeError('parameters must be set');
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
if (!parameters.code) {
|
|
141
|
-
throw new RangeError('"code" must be passed as parameter');
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
export default AuthorizationCodeFlowTokenGenerator;
|