-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenAPI.tsx
More file actions
186 lines (170 loc) · 5.53 KB
/
OpenAPI.tsx
File metadata and controls
186 lines (170 loc) · 5.53 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import React from "react";
import { BaseBatiqCore, DataSourceDefinitionSchema } from "@batiq/core";
import { Type, Static } from "@sinclair/typebox";
import OpenAPIClientAxios from "openapi-client-axios";
import { OpenAPIV3 } from "openapi-types";
import { useData } from "@batiq/expo-runtime";
import { URL as URLNative } from "react-native-url-polyfill";
import { Platform } from "react-native";
const queryDefinition = Type.Required(
Type.Object({
operationId: Type.String(),
parameters: Type.Optional(
Type.Union([
Type.Record(Type.String(), Type.Any()),
Type.Array(
Type.Object({
name: Type.String(),
value: Type.Any(),
in: Type.Union([
Type.Literal("query"),
Type.Literal("header"),
Type.Literal("path"),
Type.Literal("cookie"),
]),
})
),
])
),
data: Type.Optional(Type.Any()),
})
);
export const OpenAPI = async (data: DataSourceDefinitionSchema) => {
const { definition, auth } = data.config;
if (!definition) {
throw new Error("No definition provided");
}
const api = new OpenAPIClientAxios({ definition });
const client = await api.init();
const { origin } =
// temporary fix as react-native-url-polyfill doesn't work on web https://github.com/charpeni/react-native-url-polyfill/issues/366
// Platform.OS === "web" ? new URL(definition) : new URLNative(definition);
new URL(definition);
// eslint-disable-next-line prefer-const
let { http, apiKey, oauth2, openIdConnect } = auth;
const [securityName, securityScheme] =
Object.entries(api.document.components?.securitySchemes || {})
.filter(
(entry): entry is [string, OpenAPIV3.SecuritySchemeObject] =>
!("$ref" in entry[1])
)
.find(([, scheme]) =>
Object.entries({ http, apiKey, oauth2, openIdConnect }).some(
([key, value]) => value && scheme.type === key
)
) || [];
const operationMap: Record<string, OpenAPIV3.OperationObject> =
Object.fromEntries(
Object.values(api.document.paths || {}).flatMap((path) =>
path
? Object.values(path).map((operation) =>
!Array.isArray(operation) && typeof operation === "object"
? operation.operationId
? [operation.operationId, operation]
: []
: []
)
: []
)
);
return {
isAuthenticated: async <T extends BaseBatiqCore>(batiq: T) => {
switch (securityScheme?.type) {
case "apiKey":
return apiKey !== undefined
? true
: window?.localStorage.getItem("apiKey");
case "oauth2":
return window?.localStorage?.getItem("token") !== null;
case "openIdConnect":
return window?.localStorage?.getItem("token") !== null;
default:
return true;
}
},
authenticate: async <T extends BaseBatiqCore>(batiq: T, data: any) => {
switch (securityScheme?.type) {
case "apiKey": {
if (apiKey) {
apiKey = data.apiKey;
return;
}
window?.localStorage.setItem("apiKey", data.apiKey);
return;
}
case "oauth2": {
const { clientId } = oauth2;
const { scopes, authorizationUrl = oauth2.authorizationUrl } =
securityScheme.flows.authorizationCode || {};
const redirectUri = window.location.origin;
const url = new URL(authorizationUrl);
url.searchParams.set("client_id", clientId);
url.searchParams.set("redirect_uri", redirectUri);
url.searchParams.set("response_type", "code");
if (scopes) {
url.searchParams.set("scope", Object.keys(scopes).join(" "));
}
return;
}
case "openIdConnect": {
// Not Implemented
return;
}
default:
return;
}
},
logout: () => {
switch (securityScheme?.type) {
case "apiKey":
return apiKey !== undefined
? true
: window?.localStorage.removeItem("apiKey");
case "oauth2":
return window?.localStorage?.removeItem("token");
case "openIdConnect":
return window?.localStorage?.removeItem("token");
}
},
definition: queryDefinition,
component: (
props: React.PropsWithChildren<{
query: Static<typeof queryDefinition>;
name: string;
}>
) => {
const operation = operationMap[props.query.operationId];
if (!operation) {
throw new Error(`Operation ${props.query.operationId} not found`);
}
const config = {
baseURL: origin + (api.document.servers?.[0]?.url ?? ""),
headers:
securityScheme?.type === "apiKey"
? { "x-api-key": apiKey }
: securityScheme?.type === "http"
? {
Authorization: `Bearer ${window?.localStorage?.getItem(
"token"
)}`,
}
: {
Authorization: `Bearer ${window?.localStorage?.getItem(
"token"
)}`,
},
};
const data = useData(
props.name,
() =>
client[props.query.operationId](
props.query.parameters,
undefined,
config
).then((response) => response.data),
[client, props.query, config]
);
return props.children;
},
};
};