-
Notifications
You must be signed in to change notification settings - Fork 0
/
apilib.mustache
78 lines (66 loc) · 2.61 KB
/
apilib.mustache
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
library {{pubName}}.api;
import 'package:dio/dio.dart';
import 'package:built_value/serializer.dart';
import 'package:{{pubName}}/serializers.dart';
import 'package:{{pubName}}/auth/api_key_auth.dart';
import 'package:{{pubName}}/auth/basic_auth.dart';
import 'package:{{pubName}}/auth/oauth.dart';
{{#apiInfo}}{{#apis}}import 'package:{{pubName}}/api/{{classFilename}}.dart';
{{/apis}}{{/apiInfo}}
final _defaultInterceptors = [OAuthInterceptor(), BasicAuthInterceptor(), ApiKeyAuthInterceptor()];
class {{clientName}} {
late Dio dio;
late Serializers serializers;
final defaultBasePath = '{{{basePath}}}';
final bool fileNamesHaveBrackets;
{{clientName}}({Dio? dioOverride, Serializers? serializersOverride, String? basePathOverride, int? connectTimeoutOverride, int? receiveTimeoutOverride, List<Interceptor>? interceptorsOverride, this.fileNamesHaveBrackets=true,}) {
if (dioOverride == null) {
final options = BaseOptions(
baseUrl: basePathOverride ?? defaultBasePath,
connectTimeout: connectTimeoutOverride ?? 5000,
receiveTimeout: receiveTimeoutOverride ?? 3000,
);
this.dio = Dio(options);
}
else {
this.dio = dioOverride;
}
if (interceptorsOverride == null) {
this.dio.interceptors.addAll(_defaultInterceptors);
} else {
this.dio.interceptors.addAll(interceptorsOverride);
}
this.serializers = serializersOverride ?? standardSerializers;
}
void doForAllInterceptor<T extends Interceptor>(
void Function(T interceptor) action,
) {
for (var item in this.dio.interceptors.whereType<T>()) {
action(item);
}
}
void setOAuthToken(String name, String token) {
doForAllInterceptor<OAuthInterceptor>((item) {
item.tokens[name] = token;
});
}
void setBasicAuth(String name, String username, String password) {
doForAllInterceptor<BasicAuthInterceptor>((item) {
item.authInfo[name] = BasicAuthInfo(username, password);
});
}
void setApiKey(String name, String apiKey) {
doForAllInterceptor<ApiKeyAuthInterceptor>((item) {
item.apiKeys[name] = apiKey;
});
}
{{#apiInfo}}{{#apis}}
/**
* Get {{classname}} instance, base route and serializer can be overridden by a given but be careful,
* by doing that all interceptors will not be executed
*/
{{classname}} get{{classname}}() {
return {{classname}}(dio, serializers, fileNamesHaveBrackets);
}
{{/apis}}{{/apiInfo}}
}