react-native-appwrite 0.1.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.
Files changed (109) hide show
  1. package/.github/ISSUE_TEMPLATE/bug.yaml +82 -0
  2. package/.github/ISSUE_TEMPLATE/documentation.yaml +32 -0
  3. package/.github/ISSUE_TEMPLATE/feature.yaml +40 -0
  4. package/.github/workflows/publish.yml +33 -0
  5. package/.gitpod.yml +10 -0
  6. package/CHANGELOG.md +1 -0
  7. package/LICENSE +12 -0
  8. package/README.md +111 -0
  9. package/dist/cjs/sdk.js +3127 -0
  10. package/dist/cjs/sdk.js.map +1 -0
  11. package/dist/esm/sdk.js +3108 -0
  12. package/dist/esm/sdk.js.map +1 -0
  13. package/dist/iife/sdk.js +3126 -0
  14. package/docs/examples/account/create-anonymous-session.md +18 -0
  15. package/docs/examples/account/create-email-session.md +18 -0
  16. package/docs/examples/account/create-j-w-t.md +18 -0
  17. package/docs/examples/account/create-magic-u-r-l-session.md +18 -0
  18. package/docs/examples/account/create-o-auth2session.md +14 -0
  19. package/docs/examples/account/create-phone-session.md +18 -0
  20. package/docs/examples/account/create-phone-verification.md +18 -0
  21. package/docs/examples/account/create-recovery.md +18 -0
  22. package/docs/examples/account/create-verification.md +18 -0
  23. package/docs/examples/account/create.md +18 -0
  24. package/docs/examples/account/delete-identity.md +18 -0
  25. package/docs/examples/account/delete-session.md +18 -0
  26. package/docs/examples/account/delete-sessions.md +18 -0
  27. package/docs/examples/account/get-prefs.md +18 -0
  28. package/docs/examples/account/get-session.md +18 -0
  29. package/docs/examples/account/get.md +18 -0
  30. package/docs/examples/account/list-identities.md +18 -0
  31. package/docs/examples/account/list-logs.md +18 -0
  32. package/docs/examples/account/list-sessions.md +18 -0
  33. package/docs/examples/account/update-email.md +18 -0
  34. package/docs/examples/account/update-magic-u-r-l-session.md +18 -0
  35. package/docs/examples/account/update-name.md +18 -0
  36. package/docs/examples/account/update-password.md +18 -0
  37. package/docs/examples/account/update-phone-session.md +18 -0
  38. package/docs/examples/account/update-phone-verification.md +18 -0
  39. package/docs/examples/account/update-phone.md +18 -0
  40. package/docs/examples/account/update-prefs.md +18 -0
  41. package/docs/examples/account/update-recovery.md +18 -0
  42. package/docs/examples/account/update-session.md +18 -0
  43. package/docs/examples/account/update-status.md +18 -0
  44. package/docs/examples/account/update-verification.md +18 -0
  45. package/docs/examples/avatars/get-browser.md +14 -0
  46. package/docs/examples/avatars/get-credit-card.md +14 -0
  47. package/docs/examples/avatars/get-favicon.md +14 -0
  48. package/docs/examples/avatars/get-flag.md +14 -0
  49. package/docs/examples/avatars/get-image.md +14 -0
  50. package/docs/examples/avatars/get-initials.md +14 -0
  51. package/docs/examples/avatars/get-q-r.md +14 -0
  52. package/docs/examples/databases/create-document.md +18 -0
  53. package/docs/examples/databases/delete-document.md +18 -0
  54. package/docs/examples/databases/get-document.md +18 -0
  55. package/docs/examples/databases/list-documents.md +18 -0
  56. package/docs/examples/databases/update-document.md +18 -0
  57. package/docs/examples/functions/create-execution.md +18 -0
  58. package/docs/examples/functions/get-execution.md +18 -0
  59. package/docs/examples/functions/list-executions.md +18 -0
  60. package/docs/examples/graphql/mutation.md +18 -0
  61. package/docs/examples/graphql/query.md +18 -0
  62. package/docs/examples/locale/get.md +18 -0
  63. package/docs/examples/locale/list-codes.md +18 -0
  64. package/docs/examples/locale/list-continents.md +18 -0
  65. package/docs/examples/locale/list-countries-e-u.md +18 -0
  66. package/docs/examples/locale/list-countries-phones.md +18 -0
  67. package/docs/examples/locale/list-countries.md +18 -0
  68. package/docs/examples/locale/list-currencies.md +18 -0
  69. package/docs/examples/locale/list-languages.md +18 -0
  70. package/docs/examples/storage/create-file.md +18 -0
  71. package/docs/examples/storage/delete-file.md +18 -0
  72. package/docs/examples/storage/get-file-download.md +14 -0
  73. package/docs/examples/storage/get-file-preview.md +14 -0
  74. package/docs/examples/storage/get-file-view.md +14 -0
  75. package/docs/examples/storage/get-file.md +18 -0
  76. package/docs/examples/storage/list-files.md +18 -0
  77. package/docs/examples/storage/update-file.md +18 -0
  78. package/docs/examples/teams/create-membership.md +18 -0
  79. package/docs/examples/teams/create.md +18 -0
  80. package/docs/examples/teams/delete-membership.md +18 -0
  81. package/docs/examples/teams/delete.md +18 -0
  82. package/docs/examples/teams/get-membership.md +18 -0
  83. package/docs/examples/teams/get-prefs.md +18 -0
  84. package/docs/examples/teams/get.md +18 -0
  85. package/docs/examples/teams/list-memberships.md +18 -0
  86. package/docs/examples/teams/list.md +18 -0
  87. package/docs/examples/teams/update-membership-status.md +18 -0
  88. package/docs/examples/teams/update-membership.md +18 -0
  89. package/docs/examples/teams/update-name.md +18 -0
  90. package/docs/examples/teams/update-prefs.md +18 -0
  91. package/package.json +47 -0
  92. package/rollup.config.js +31 -0
  93. package/src/client.ts +437 -0
  94. package/src/id.ts +9 -0
  95. package/src/index.ts +14 -0
  96. package/src/models.ts +1021 -0
  97. package/src/permission.ts +22 -0
  98. package/src/query.ts +74 -0
  99. package/src/role.ts +100 -0
  100. package/src/service.ts +30 -0
  101. package/src/services/account.ts +1066 -0
  102. package/src/services/avatars.ts +352 -0
  103. package/src/services/databases.ts +216 -0
  104. package/src/services/functions.ts +125 -0
  105. package/src/services/graphql.ts +68 -0
  106. package/src/services/locale.ts +169 -0
  107. package/src/services/storage.ts +411 -0
  108. package/src/services/teams.ts +484 -0
  109. package/tsconfig.json +24 -0
@@ -0,0 +1,18 @@
1
+ import { Client, Teams } from "appwrite";
2
+
3
+ const client = new Client();
4
+
5
+ const teams = new Teams(client);
6
+
7
+ client
8
+ .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint
9
+ .setProject('5df5acd0d48c2') // Your project ID
10
+ ;
11
+
12
+ const promise = teams.get('[TEAM_ID]');
13
+
14
+ promise.then(function (response) {
15
+ console.log(response); // Success
16
+ }, function (error) {
17
+ console.log(error); // Failure
18
+ });
@@ -0,0 +1,18 @@
1
+ import { Client, Teams } from "appwrite";
2
+
3
+ const client = new Client();
4
+
5
+ const teams = new Teams(client);
6
+
7
+ client
8
+ .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint
9
+ .setProject('5df5acd0d48c2') // Your project ID
10
+ ;
11
+
12
+ const promise = teams.listMemberships('[TEAM_ID]');
13
+
14
+ promise.then(function (response) {
15
+ console.log(response); // Success
16
+ }, function (error) {
17
+ console.log(error); // Failure
18
+ });
@@ -0,0 +1,18 @@
1
+ import { Client, Teams } from "appwrite";
2
+
3
+ const client = new Client();
4
+
5
+ const teams = new Teams(client);
6
+
7
+ client
8
+ .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint
9
+ .setProject('5df5acd0d48c2') // Your project ID
10
+ ;
11
+
12
+ const promise = teams.list();
13
+
14
+ promise.then(function (response) {
15
+ console.log(response); // Success
16
+ }, function (error) {
17
+ console.log(error); // Failure
18
+ });
@@ -0,0 +1,18 @@
1
+ import { Client, Teams } from "appwrite";
2
+
3
+ const client = new Client();
4
+
5
+ const teams = new Teams(client);
6
+
7
+ client
8
+ .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint
9
+ .setProject('5df5acd0d48c2') // Your project ID
10
+ ;
11
+
12
+ const promise = teams.updateMembershipStatus('[TEAM_ID]', '[MEMBERSHIP_ID]', '[USER_ID]', '[SECRET]');
13
+
14
+ promise.then(function (response) {
15
+ console.log(response); // Success
16
+ }, function (error) {
17
+ console.log(error); // Failure
18
+ });
@@ -0,0 +1,18 @@
1
+ import { Client, Teams } from "appwrite";
2
+
3
+ const client = new Client();
4
+
5
+ const teams = new Teams(client);
6
+
7
+ client
8
+ .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint
9
+ .setProject('5df5acd0d48c2') // Your project ID
10
+ ;
11
+
12
+ const promise = teams.updateMembership('[TEAM_ID]', '[MEMBERSHIP_ID]', []);
13
+
14
+ promise.then(function (response) {
15
+ console.log(response); // Success
16
+ }, function (error) {
17
+ console.log(error); // Failure
18
+ });
@@ -0,0 +1,18 @@
1
+ import { Client, Teams } from "appwrite";
2
+
3
+ const client = new Client();
4
+
5
+ const teams = new Teams(client);
6
+
7
+ client
8
+ .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint
9
+ .setProject('5df5acd0d48c2') // Your project ID
10
+ ;
11
+
12
+ const promise = teams.updateName('[TEAM_ID]', '[NAME]');
13
+
14
+ promise.then(function (response) {
15
+ console.log(response); // Success
16
+ }, function (error) {
17
+ console.log(error); // Failure
18
+ });
@@ -0,0 +1,18 @@
1
+ import { Client, Teams } from "appwrite";
2
+
3
+ const client = new Client();
4
+
5
+ const teams = new Teams(client);
6
+
7
+ client
8
+ .setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint
9
+ .setProject('5df5acd0d48c2') // Your project ID
10
+ ;
11
+
12
+ const promise = teams.updatePrefs('[TEAM_ID]', {});
13
+
14
+ promise.then(function (response) {
15
+ console.log(response); // Success
16
+ }, function (error) {
17
+ console.log(error); // Failure
18
+ });
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "react-native-appwrite",
3
+ "homepage": "https://appwrite.io/support",
4
+ "description": "Appwrite is an open-source self-hosted backend server that abstract and simplify complex and repetitive development tasks behind a very simple REST API",
5
+ "version": "0.1.0",
6
+ "license": "BSD-3-Clause",
7
+ "main": "dist/cjs/sdk.js",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/esm/sdk.js",
11
+ "require": "./dist/cjs/sdk.js",
12
+ "types": "./types/index.d.ts"
13
+ },
14
+ "./package.json": "./package.json"
15
+ },
16
+ "module": "dist/esm/sdk.js",
17
+ "types": "types/index.d.ts",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/appwrite/sdk-for-react-native"
21
+ },
22
+ "scripts": {
23
+ "build": "npm run build:types && npm run build:libs",
24
+ "build:types": "tsc --declaration --emitDeclarationOnly --outDir types",
25
+ "build:libs": "rollup -c"
26
+ },
27
+ "devDependencies": {
28
+ "@rollup/plugin-typescript": "8.3.2",
29
+ "playwright": "1.15.0",
30
+ "rollup": "2.75.4",
31
+ "serve-handler": "6.1.0",
32
+ "tslib": "2.4.0",
33
+ "react-native-fs": "^2.20.0",
34
+ "typescript": "4.7.2"
35
+ },
36
+ "dependencies": {
37
+ "cross-fetch": "3.1.5",
38
+ "isomorphic-form-data": "2.0.0"
39
+ },
40
+ "peerDependencies": {
41
+ "react-native": "*",
42
+ "react-native-fs": "^2.20.0",
43
+ "react-native-url-polyfill": "^2.0.0"
44
+ },
45
+ "jsdelivr": "dist/iife/sdk.js",
46
+ "unpkg": "dist/iife/sdk.js"
47
+ }
@@ -0,0 +1,31 @@
1
+ import pkg from "./package.json";
2
+ import typescript from "@rollup/plugin-typescript";
3
+
4
+ export default {
5
+ external: Object.keys(pkg.dependencies),
6
+ input: "src/index.ts",
7
+ plugins: [typescript()],
8
+ output: [
9
+ {
10
+ format: "cjs",
11
+ file: pkg.main,
12
+ esModule: false,
13
+ sourcemap: true,
14
+ },
15
+ {
16
+ format: "es",
17
+ file: pkg.module,
18
+ sourcemap: true,
19
+ },
20
+ {
21
+ format: "iife",
22
+ file: pkg.jsdelivr,
23
+ name: "Appwrite",
24
+ extend: true,
25
+ globals: {
26
+ "cross-fetch": "window",
27
+ "FormData": "FormData",
28
+ },
29
+ },
30
+ ],
31
+ };
package/src/client.ts ADDED
@@ -0,0 +1,437 @@
1
+ import 'isomorphic-form-data';
2
+ import { fetch } from 'cross-fetch';
3
+ import { Platform } from 'react-native';
4
+ import { Models } from './models';
5
+ import { Service } from './service';
6
+
7
+ type Payload = {
8
+ [key: string]: any;
9
+ }
10
+
11
+ type Headers = {
12
+ [key: string]: string;
13
+ }
14
+
15
+ type RealtimeResponse = {
16
+ type: 'error' | 'event' | 'connected' | 'response';
17
+ data: RealtimeResponseAuthenticated | RealtimeResponseConnected | RealtimeResponseError | RealtimeResponseEvent<unknown>;
18
+ }
19
+
20
+ type RealtimeRequest = {
21
+ type: 'authentication';
22
+ data: RealtimeRequestAuthenticate;
23
+ }
24
+
25
+ export type RealtimeResponseEvent<T extends unknown> = {
26
+ events: string[];
27
+ channels: string[];
28
+ timestamp: number;
29
+ payload: T;
30
+ }
31
+
32
+ type RealtimeResponseError = {
33
+ code: number;
34
+ message: string;
35
+ }
36
+
37
+ type RealtimeResponseConnected = {
38
+ channels: string[];
39
+ user?: object;
40
+ }
41
+
42
+ type RealtimeResponseAuthenticated = {
43
+ to: string;
44
+ success: boolean;
45
+ user: object;
46
+ }
47
+
48
+ type RealtimeRequestAuthenticate = {
49
+ session: string;
50
+ }
51
+
52
+ type Realtime = {
53
+ socket?: WebSocket;
54
+ timeout?: number;
55
+ url?: string;
56
+ lastMessage?: RealtimeResponse;
57
+ channels: Set<string>;
58
+ subscriptions: Map<number, {
59
+ channels: string[];
60
+ callback: (payload: RealtimeResponseEvent<any>) => void
61
+ }>;
62
+ subscriptionsCounter: number;
63
+ reconnect: boolean;
64
+ reconnectAttempts: number;
65
+ getTimeout: () => number;
66
+ connect: () => void;
67
+ createSocket: () => void;
68
+ cleanUp: (channels: string[]) => void;
69
+ onMessage: (event: MessageEvent) => void;
70
+ }
71
+
72
+ export type UploadProgress = {
73
+ $id: string;
74
+ progress: number;
75
+ sizeUploaded: number;
76
+ chunksTotal: number;
77
+ chunksUploaded: number;
78
+ }
79
+
80
+ class AppwriteException extends Error {
81
+ code: number;
82
+ response: string;
83
+ type: string;
84
+ constructor(message: string, code: number = 0, type: string = '', response: string = '') {
85
+ super(message);
86
+ this.name = 'AppwriteException';
87
+ this.message = message;
88
+ this.code = code;
89
+ this.type = type;
90
+ this.response = response;
91
+ }
92
+ }
93
+
94
+ class Client {
95
+ config = {
96
+ endpoint: 'https://HOSTNAME/v1',
97
+ endpointRealtime: '',
98
+ project: '',
99
+ jwt: '',
100
+ locale: '',
101
+ platform: '',
102
+ };
103
+ headers: Headers = {
104
+ 'x-sdk-name': 'Web',
105
+ 'x-sdk-platform': 'client',
106
+ 'x-sdk-language': 'web',
107
+ 'x-sdk-version': '13.0.2',
108
+ 'X-Appwrite-Response-Format': '1.4.0',
109
+ };
110
+
111
+ /**
112
+ * Set Endpoint
113
+ *
114
+ * Your project endpoint
115
+ *
116
+ * @param {string} endpoint
117
+ *
118
+ * @returns {this}
119
+ */
120
+ setEndpoint(endpoint: string): this {
121
+ this.config.endpoint = endpoint;
122
+ this.config.endpointRealtime = this.config.endpointRealtime || this.config.endpoint.replace('https://', 'wss://').replace('http://', 'ws://');
123
+
124
+ return this;
125
+ }
126
+
127
+ /**
128
+ * Set Realtime Endpoint
129
+ *
130
+ * @param {string} endpointRealtime
131
+ *
132
+ * @returns {this}
133
+ */
134
+ setEndpointRealtime(endpointRealtime: string): this {
135
+ this.config.endpointRealtime = endpointRealtime;
136
+
137
+ return this;
138
+ }
139
+
140
+ /**
141
+ * Set platform
142
+ *
143
+ * Set platform. Will be used as origin for all requests.
144
+ *
145
+ * @param {string} platform
146
+ * @returns {this}
147
+ */
148
+ setPlatform(platform: string): this {
149
+ this.config.platform = platform;
150
+
151
+ return this;
152
+ }
153
+
154
+ /**
155
+ * Set Project
156
+ *
157
+ * Your project ID
158
+ *
159
+ * @param value string
160
+ *
161
+ * @return {this}
162
+ */
163
+ setProject(value: string): this {
164
+ this.headers['X-Appwrite-Project'] = value;
165
+ this.config.project = value;
166
+ return this;
167
+ }
168
+
169
+ /**
170
+ * Set JWT
171
+ *
172
+ * Your secret JSON Web Token
173
+ *
174
+ * @param value string
175
+ *
176
+ * @return {this}
177
+ */
178
+ setJWT(value: string): this {
179
+ this.headers['X-Appwrite-JWT'] = value;
180
+ this.config.jwt = value;
181
+ return this;
182
+ }
183
+
184
+ /**
185
+ * Set Locale
186
+ *
187
+ * @param value string
188
+ *
189
+ * @return {this}
190
+ */
191
+ setLocale(value: string): this {
192
+ this.headers['X-Appwrite-Locale'] = value;
193
+ this.config.locale = value;
194
+ return this;
195
+ }
196
+
197
+
198
+ private realtime: Realtime = {
199
+ socket: undefined,
200
+ timeout: undefined,
201
+ url: '',
202
+ channels: new Set(),
203
+ subscriptions: new Map(),
204
+ subscriptionsCounter: 0,
205
+ reconnect: true,
206
+ reconnectAttempts: 0,
207
+ lastMessage: undefined,
208
+ connect: () => {
209
+ clearTimeout(this.realtime.timeout);
210
+ this.realtime.timeout = window?.setTimeout(() => {
211
+ this.realtime.createSocket();
212
+ }, 50);
213
+ },
214
+ getTimeout: () => {
215
+ switch (true) {
216
+ case this.realtime.reconnectAttempts < 5:
217
+ return 1000;
218
+ case this.realtime.reconnectAttempts < 15:
219
+ return 5000;
220
+ case this.realtime.reconnectAttempts < 100:
221
+ return 10_000;
222
+ default:
223
+ return 60_000;
224
+ }
225
+ },
226
+ createSocket: () => {
227
+ if (this.realtime.channels.size < 1) return;
228
+
229
+ const channels = new URLSearchParams();
230
+ channels.set('project', this.config.project);
231
+ this.realtime.channels.forEach(channel => {
232
+ channels.append('channels[]', channel);
233
+ });
234
+
235
+ const url = this.config.endpointRealtime + '/realtime?' + channels.toString();
236
+
237
+ if (
238
+ url !== this.realtime.url || // Check if URL is present
239
+ !this.realtime.socket || // Check if WebSocket has not been created
240
+ this.realtime.socket?.readyState > WebSocket.OPEN // Check if WebSocket is CLOSING (3) or CLOSED (4)
241
+ ) {
242
+ if (
243
+ this.realtime.socket &&
244
+ this.realtime.socket?.readyState < WebSocket.CLOSING // Close WebSocket if it is CONNECTING (0) or OPEN (1)
245
+ ) {
246
+ this.realtime.reconnect = false;
247
+ this.realtime.socket.close();
248
+ }
249
+
250
+ this.realtime.url = url;
251
+ // @ts-ignore
252
+ this.realtime.socket = new WebSocket(url, undefined, {
253
+ headers: {
254
+ Origin: `appwrite-${Platform.OS}://${this.config.platform}`
255
+ }
256
+ });
257
+ this.realtime.socket.addEventListener('message', this.realtime.onMessage);
258
+ this.realtime.socket.addEventListener('open', _event => {
259
+ this.realtime.reconnectAttempts = 0;
260
+ });
261
+ this.realtime.socket.addEventListener('close', event => {
262
+ if (
263
+ !this.realtime.reconnect ||
264
+ (
265
+ this.realtime?.lastMessage?.type === 'error' && // Check if last message was of type error
266
+ (<RealtimeResponseError>this.realtime?.lastMessage.data).code === 1008 // Check for policy violation 1008
267
+ )
268
+ ) {
269
+ this.realtime.reconnect = true;
270
+ return;
271
+ }
272
+
273
+ const timeout = this.realtime.getTimeout();
274
+ console.error(`Realtime got disconnected. Reconnect will be attempted in ${timeout / 1000} seconds.`, event.reason);
275
+
276
+ setTimeout(() => {
277
+ this.realtime.reconnectAttempts++;
278
+ this.realtime.createSocket();
279
+ }, timeout);
280
+ })
281
+ }
282
+ },
283
+ onMessage: async (event) => {
284
+ try {
285
+ const message: RealtimeResponse = JSON.parse(event.data);
286
+ this.realtime.lastMessage = message;
287
+ switch (message.type) {
288
+ case 'event':
289
+ let data = <RealtimeResponseEvent<unknown>>message.data;
290
+ if (data?.channels) {
291
+ const isSubscribed = data.channels.some(channel => this.realtime.channels.has(channel));
292
+ if (!isSubscribed) return;
293
+ this.realtime.subscriptions.forEach(subscription => {
294
+ if (data.channels.some(channel => subscription.channels.includes(channel))) {
295
+ setTimeout(() => subscription.callback(data));
296
+ }
297
+ })
298
+ }
299
+ break;
300
+ case 'error':
301
+ throw message.data;
302
+ default:
303
+ break;
304
+ }
305
+ } catch (e) {
306
+ console.error(e);
307
+ }
308
+ },
309
+ cleanUp: channels => {
310
+ this.realtime.channels.forEach(channel => {
311
+ if (channels.includes(channel)) {
312
+ let found = Array.from(this.realtime.subscriptions).some(([_key, subscription]) => {
313
+ return subscription.channels.includes(channel);
314
+ })
315
+
316
+ if (!found) {
317
+ this.realtime.channels.delete(channel);
318
+ }
319
+ }
320
+ })
321
+ }
322
+ }
323
+
324
+ /**
325
+ * Subscribes to Appwrite events and passes you the payload in realtime.
326
+ *
327
+ * @param {string|string[]} channels
328
+ * Channel to subscribe - pass a single channel as a string or multiple with an array of strings.
329
+ *
330
+ * Possible channels are:
331
+ * - account
332
+ * - collections
333
+ * - collections.[ID]
334
+ * - collections.[ID].documents
335
+ * - documents
336
+ * - documents.[ID]
337
+ * - files
338
+ * - files.[ID]
339
+ * - executions
340
+ * - executions.[ID]
341
+ * - functions.[ID]
342
+ * - teams
343
+ * - teams.[ID]
344
+ * - memberships
345
+ * - memberships.[ID]
346
+ * @param {(payload: RealtimeMessage) => void} callback Is called on every realtime update.
347
+ * @returns {() => void} Unsubscribes from events.
348
+ */
349
+ subscribe<T extends unknown>(channels: string | string[], callback: (payload: RealtimeResponseEvent<T>) => void): () => void {
350
+ let channelArray = typeof channels === 'string' ? [channels] : channels;
351
+ channelArray.forEach(channel => this.realtime.channels.add(channel));
352
+
353
+ const counter = this.realtime.subscriptionsCounter++;
354
+ this.realtime.subscriptions.set(counter, {
355
+ channels: channelArray,
356
+ callback
357
+ });
358
+
359
+ this.realtime.connect();
360
+
361
+ return () => {
362
+ this.realtime.subscriptions.delete(counter);
363
+ this.realtime.cleanUp(channelArray);
364
+ this.realtime.connect();
365
+ }
366
+ }
367
+
368
+ async call(method: string, url: URL, headers: Headers = {}, params: Payload = {}): Promise<any> {
369
+ method = method.toUpperCase();
370
+
371
+ headers = Object.assign({}, this.headers, headers);
372
+ headers.Origin = `appwrite-${Platform.OS}://${this.config.platform}`;
373
+ let options: RequestInit = {
374
+ method,
375
+ headers,
376
+ credentials: 'include'
377
+ };
378
+
379
+ if (method === 'GET') {
380
+ for (const [key, value] of Object.entries(Service.flatten(params))) {
381
+ url.searchParams.append(key, value);
382
+ }
383
+ } else {
384
+ switch (headers['content-type']) {
385
+ case 'application/json':
386
+ options.body = JSON.stringify(params);
387
+ break;
388
+
389
+ case 'multipart/form-data':
390
+ let formData = new FormData();
391
+
392
+ for (const key in params) {
393
+ if (Array.isArray(params[key])) {
394
+ params[key].forEach((value: any) => {
395
+ formData.append(key + '[]', value);
396
+ })
397
+ } else {
398
+ formData.append(key, params[key]);
399
+ }
400
+ }
401
+
402
+ options.body = formData;
403
+ delete headers['content-type'];
404
+ break;
405
+ }
406
+ }
407
+
408
+ try {
409
+ let data = null;
410
+ const response = await fetch(url.toString(), options);
411
+
412
+ if (response.headers.get('content-type')?.includes('application/json')) {
413
+ data = await response.json();
414
+ } else {
415
+ data = {
416
+ message: await response.text()
417
+ };
418
+ }
419
+
420
+ if (400 <= response.status) {
421
+ throw new AppwriteException(data?.message, response.status, data?.type, data);
422
+ }
423
+
424
+ return data;
425
+ } catch (e) {
426
+ if (e instanceof AppwriteException) {
427
+ throw e;
428
+ }
429
+ throw new AppwriteException((<Error>e).message);
430
+ }
431
+ }
432
+ }
433
+
434
+ export { Client, AppwriteException };
435
+ export { Query } from './query';
436
+ export type { Models, Payload };
437
+ export type { QueryTypes, QueryTypesList } from './query';
package/src/id.ts ADDED
@@ -0,0 +1,9 @@
1
+ export class ID {
2
+ public static custom(id: string): string {
3
+ return id
4
+ }
5
+
6
+ public static unique(): string {
7
+ return 'unique()'
8
+ }
9
+ }
package/src/index.ts ADDED
@@ -0,0 +1,14 @@
1
+ export { Client, Query, AppwriteException } from './client';
2
+ export { Account } from './services/account';
3
+ export { Avatars } from './services/avatars';
4
+ export { Databases } from './services/databases';
5
+ export { Functions } from './services/functions';
6
+ export { Graphql } from './services/graphql';
7
+ export { Locale } from './services/locale';
8
+ export { Storage } from './services/storage';
9
+ export { Teams } from './services/teams';
10
+ export type { Models, Payload, RealtimeResponseEvent, UploadProgress } from './client';
11
+ export type { QueryTypes, QueryTypesList } from './query';
12
+ export { Permission } from './permission';
13
+ export { Role } from './role';
14
+ export { ID } from './id';