/
realms.ts
216 lines (195 loc) · 5.65 KB
/
realms.ts
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2018 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import * as Realm from 'realm';
import * as crypto from 'crypto';
import * as fs from 'fs-extra';
import * as path from 'path';
import { fetchAuthenticated, IRealmFile, RealmType, UserStatus } from '.';
import { showError } from '../../ui/reusable/errors';
export interface ISslConfiguration {
validateCertificates: boolean;
errorCallback?: Realm.Sync.ErrorCallback;
certificatePath?: string;
}
export const defaultSyncErrorCallback = (sender: any, err: any) => {
showError('Error while synchronizing Realm', err);
};
export const getUrl = (user: Realm.Sync.User, realmPath: string) => {
const url = new URL(realmPath, user.server);
url.protocol = url.protocol === 'https:' ? 'realms:' : 'realm:';
return url.toString();
};
export const open = async (params: {
user: Realm.Sync.User;
realmPath: string;
encryptionKey?: Uint8Array;
ssl: ISslConfiguration;
progressCallback?: Realm.Sync.ProgressNotificationCallback;
schema?: Realm.ObjectSchema[];
}): Promise<Realm> => {
const ssl = params.ssl || { validateCertificates: true };
const url = getUrl(params.user, params.realmPath);
let clientResetOcurred = false;
const realmPromise = Realm.open({
encryptionKey: params.encryptionKey,
schema: params.schema,
path: getPathOnDisk(params.user, params.realmPath),
sync: {
url,
user: params.user,
error: (session, error) => {
if (error.name === 'ClientReset') {
clientResetOcurred = true;
} else {
(ssl.errorCallback || defaultSyncErrorCallback)(session, error);
}
},
validate_ssl: ssl.validateCertificates,
ssl_trust_certificate_path: ssl.certificatePath,
_disableQueryBasedSyncUrlChecks: true,
},
});
if (params.progressCallback) {
realmPromise.progress(params.progressCallback);
}
const realm = await realmPromise;
if (clientResetOcurred) {
realm.close();
Realm.Sync.initiateClientReset(realm.path);
return open(params);
}
return realm;
};
// We rewrite the path on disk on Windows because default realm paths
// may hit the 260 character limits, especially with partial realms.
const getPathOnDisk = (
user: Realm.Sync.User,
realmPath: string,
): string | undefined => {
// Only Windows have path limits, so it's fine to default to whatever OS generates.
if (process.platform === 'win32') {
const userPath = path.join(process.cwd(), user.identity);
fs.ensureDirSync(userPath);
return path.join(
userPath,
crypto
.createHash('md5')
.update(realmPath)
.digest('hex'),
);
}
};
export const create = (
user: Realm.Sync.User,
realmPath: string,
schema: Realm.ObjectSchema[] = [],
validateCertificates = true,
): Promise<Realm> => {
return new Promise((resolve, reject) => {
const url = getUrl(user, realmPath);
// Using the async Realm.open to allow the caller to know when the Realm to got uploaded
Realm.open({
sync: {
user,
url,
error: (session, err) => {
reject(err);
},
ssl: { validate: validateCertificates },
},
schema,
path: getPathOnDisk(user, realmPath),
}).then(resolve, reject);
});
};
export const remove = async (user: Realm.Sync.User, realmPath: string) => {
const encodedPath = encodeURIComponent(realmPath);
return fetchAuthenticated(
user,
`/realms/files/${encodedPath}`,
{ method: 'DELETE' },
`Could not remove Realm`,
);
};
export const changeType = async (
user: Realm.Sync.User,
realmPath: string,
type: RealmType,
) => {
const encodedPath = encodeURIComponent(realmPath);
return fetchAuthenticated(
user,
`/realms/files/${encodedPath}`,
{
method: 'PATCH',
body: JSON.stringify({
realmType: type,
}),
},
'Failed to change type of the Realm',
);
};
export const update = (realmId: string, values: Partial<IRealmFile>) => {
throw new Error('Not yet implemented');
};
export const updateUserStatus = async (
user: Realm.Sync.User,
userId: string,
status: UserStatus,
) => {
return fetchAuthenticated(
user,
`/auth/users/${userId}`,
{
method: 'PATCH',
body: JSON.stringify({
status,
}),
},
'Failed to update the user status',
);
};
interface IStatisticsResponse {
[metricName: string]: Array<{
labels: { [name: string]: string };
value: number;
}>;
}
export const getStats = async (
user: Realm.Sync.User,
metricNames: string,
): Promise<IStatisticsResponse> => {
return fetchAuthenticated(
user,
`/stats/instant/${metricNames}`,
{ method: 'GET' },
'Failed to get statistics',
);
};
export const requestSizeRecalculation = (
user: Realm.Sync.User,
realmPath: string,
): Promise<void> => {
const encodedPath = encodeURIComponent(realmPath);
return fetchAuthenticated(
user,
`/realms/calculate-size/${encodedPath}`,
{ method: 'POST' },
'Failed to request size recalculation',
);
};