UNPKG

realm

Version:

Realm by MongoDB is an offline-first mobile database: an alternative to SQLite and key-value stores

304 lines 11.5 kB
"use strict"; //////////////////////////////////////////////////////////////////////////// // // Copyright 2022 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. // //////////////////////////////////////////////////////////////////////////// Object.defineProperty(exports, "__esModule", { value: true }); exports.User = exports.UserState = void 0; const internal_1 = require("../internal"); /** * The state of a user. */ var UserState; (function (UserState) { /** * Authenticated and available to communicate with services. * @deprecated Will be removed in v13. Please use {@link UserState.LoggedIn} */ UserState["Active"] = "active"; /** Authenticated and available to communicate with services. */ UserState["LoggedIn"] = "LoggedIn"; /** Logged out, but ready to be logged in. */ UserState["LoggedOut"] = "LoggedOut"; /** Removed from the app entirely. */ UserState["Removed"] = "Removed"; })(UserState = exports.UserState || (exports.UserState = {})); /** * Representation of an authenticated user of an {@link App}. */ class User { /** @internal */ app; /** @internal */ internal; // cached version of profile cachedProfile; listeners = new internal_1.Listeners({ add: (callback) => { return this.internal.subscribe(callback); }, remove: (token) => { this.internal.unsubscribe(token); }, }); /** @internal */ static get(internal, app) { // Update the static user reference to the current app if (app) { internal_1.App.setAppByUser(internal, app); } // TODO: Use a WeakRef to memoize the SDK object return new User(internal, internal_1.App.getAppByUser(internal)); } /** @internal */ constructor(internal, app) { this.internal = internal; this.app = app; this.cachedProfile = undefined; } /** * The automatically-generated internal ID of the user. * @returns The user ID as a string. */ get id() { return this.internal.identity; } /** * The provider type used when authenticating the user. If multiple identities exist, * the provider type for the first identity found is return. * @returns The provider type as an enumerated string. * @deprecated Use {@link identities} instead. */ get providerType() { const [identity] = this.internal.identities; if (!identity) { throw new Error("No provider found"); } const type = identity.providerType; if ((0, internal_1.isProviderType)(type)) { return type; } throw new Error(`Unexpected provider type: ${type}`); } /** * The ID of the device. * @returns The device ID as a string or `null`. */ get deviceId() { return this.internal.deviceId; } /** * The state of the user. * @returns The state as an enumerated string. */ get state() { const state = this.internal.state; switch (state) { case 1 /* binding.SyncUserState.LoggedIn */: return UserState.LoggedIn; case 0 /* binding.SyncUserState.LoggedOut */: return UserState.LoggedOut; case 2 /* binding.SyncUserState.Removed */: return UserState.Removed; default: throw new Error(`Unsupported SyncUserState value: ${state}`); } } /** * The logged in state of the user. * @returns `true` if the user is logged in, `false` otherwise. */ get isLoggedIn() { return this.internal.isLoggedIn; } /** * The identities of the user at any of the app's authentication providers. * @returns An array of {@link UserIdentity} objects. */ get identities() { return this.internal.identities.map(({ id, providerType }) => ({ id, providerType })); } /** * The access token used when requesting a new access token. * @returns The access token as a string or `null`. */ get accessToken() { return this.internal.accessToken; } /** * The refresh token used when requesting a new access token. * @returns The refresh token as a string or `null`. */ get refreshToken() { return this.internal.refreshToken; } /** * You can store arbitrary data about your application users in a MongoDB collection and configure * Atlas App Services to automatically expose each user’s data in a field of their user object. * For example, you might store a user’s preferred language, date of birth, or their local timezone. * * If this value has not been configured, it will be empty. * @returns The custom data as an object. */ get customData() { const result = this.internal.customData; if (result === undefined) { return {}; } return result; } /** * A profile containing additional information about the user. * @returns The user profile data as an object. */ get profile() { if (!this.cachedProfile) { this.cachedProfile = this.internal.userProfile.data(); } return this.cachedProfile; } /** * Use this to call functions defined by the Atlas App Services application, as this user. * @returns A {@link FunctionsFactory} that can be used to call the app's functions. */ get functions() { return (0, internal_1.createFactory)(this, undefined); } /** * Perform operations related to the API-key auth provider. * @returns An {@link ApiKeyAuth} object that can be used to manage API keys. */ get apiKeys() { // TODO: Add memoization const internal = this.app.internal.userApiKeyProviderClient(); return new internal_1.ApiKeyAuth(this.internal, internal); } /** * Log out the user. * @returns A promise that resolves once the user has been logged out of the app. */ async logOut() { await this.app.internal.logOutUser(this.internal); } /** * Link the user with an identity represented by another set of credentials. * @param credentials - The credentials to use when linking. * @returns A promise that resolves once the user has been linked with the credentials. */ async linkCredentials(credentials) { await this.app.internal.linkUser(this.internal, credentials.internal); } /** * Call a remote Atlas App Services Function by its name. * @note Consider using `functions[name]()` instead of calling this method. * @param name - Name of the App Services Function. * @param args - Arguments passed to the Function. * @returns A promise that resolves to the value returned by the Function. * @example * // These are all equivalent: * await user.callFunction("doThing", a1, a2, a3); * await user.functions.doThing(a1, a2, a3); * await user.functions["doThing"](a1, a2, a3); * @example * // The methods returned from the functions object are bound, which is why it's okay to store the function in a variable before calling it: * const doThing = user.functions.doThing; * await doThing(a1); * await doThing(a2); */ callFunction(name, ...args) { return this.callFunctionOnService(name, undefined, ...args); } /** @internal */ async callFunctionOnService(name, serviceName, ...args) { return this.app.internal.callFunction(this.internal, name, (0, internal_1.cleanArguments)(args), serviceName); } /** @internal */ async callFunctionStreaming(functionName, serviceName, ...functionArgs) { const request = this.app.internal.makeStreamingRequest(this.internal, functionName, (0, internal_1.cleanArguments)(functionArgs), serviceName); const response = await internal_1.network.fetch(...internal_1.binding.toFetchArgs(request)); (0, internal_1.assert)(response.ok, () => `Request failed: ${response.statusText} (${response.status})`); (0, internal_1.assert)(response.body, "Expected a body in the response"); return (0, internal_1.asyncIteratorFromResponse)(response); } /** * Refresh the access token and derive custom data from it. * @returns A promise that resolves to the refreshed custom data. */ async refreshCustomData() { await this.app.internal.refreshCustomData(this.internal); return this.customData; } /** * Use the Push service to enable sending push messages to this user via Firebase Cloud Messaging (FCM). * @deprecated https://www.mongodb.com/docs/atlas/app-services/reference/push-notifications/ * @returns A {@link PushClient} with methods to register and deregister the device on the user. */ push(serviceName) { const internal = this.app.internal.pushNotificationClient(serviceName); return new internal_1.PushClient(this.internal, internal); } /** * @param serviceName - The name of the MongoDB service to connect to. * @returns A client enabling access to a {@link MongoDB} service. * @example * let blueWidgets = user.mongoClient("myService") * .db("myDb") * .collection<Widget>("widgets") * .find({ color: "blue" }); */ mongoClient(serviceName) { internal_1.assert.string(serviceName, "serviceName"); (0, internal_1.assert)(serviceName.length, "Please provide the name of the MongoDB service to connect to."); return { get serviceName() { return serviceName; }, db: (databaseName) => { return { get name() { return databaseName; }, collection: (collectionName) => { return new internal_1.MongoDBCollection(this, serviceName, databaseName, collectionName); }, }; }, }; } /** * Adds a listener that will be fired on various user related events. * This includes auth token refresh, refresh token refresh, refresh custom user data, and logout. * @param callback - The callback to be fired when the event occurs. */ addListener(callback) { this.listeners.add(callback); } /** * Removes an event listener previously added via {@link User.addListener}. * @param callback - The callback to be removed. */ removeListener(callback) { this.listeners.remove(callback); } /** * Removes all event listeners previously added via {@link User.addListener}. */ removeAllListeners() { this.listeners.removeAll(); } } exports.User = User; //# sourceMappingURL=User.js.map