Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
SDK de Dispositivo Atlas

Get Started with Realm Web & Atlas Device Sync (Preview)

The Realm JavaScript SDK with WebAssembly support allows you to build realtime web applications for the browser using the Realm Database API and Atlas Device Sync.

Importante

El SDK de Realm JS compatible con WebAssembly está en versión preliminar. Actualmente presenta limitaciones significativas en comparación con el SDK de Realm JS para Node.js o React Native. Consulte Sección de limitaciones para obtener más información.

La forma más rápida de empezar a usar el SDK de WebAssembly de Realm JS es clonar y ejecutar nuestra aplicación de ejemplo de sincronización web prediseñada. La aplicación está escrita en React y utiliza las API de base de datos de Realm y la sincronización de dispositivos Atlas.

1

To get started, clone the example app repository, checkout the example app branch, and navigate to the example project:

git clone https://github.com/realm/realm-js.git
cd realm-js
git checkout nh/wasm/emscripten_target
cd examples/example-react-task
2

Desde el directorio raíz de la app de ejemplo, ejecuta el siguiente comando para instalar dependencias, incluido el SDK de Realm JS con WebAssembly:

npm install

Nota

La aplicación de ejemplo actualmente admite la instalación con npmSi utiliza yarn o pnpm, es posible que deba proporcionar polyfills adicionales.

3

To use Device Sync, you must connect to an App Services App that has Device Sync enabled. Follow the App creation instructions in the example project's README.md file. Once you've created and configured the App, copy its Client App ID and paste it into the src/atlas-app-services/config.json file in the example project:

src/atlas-app-services/config.json
{
"ATLAS_APP_ID": "myapp-abcde"
}
4

Now that you've installed dependencies and defined the connection to your App, you can run the example app:

npm start

You can install the Realm JS SDK with WebAssembly support from npm:

npm install realm@12.0.0-browser.2

Nota

The Realm JS SDK with WebAssembly support is currently only available as a tagged release of the realm package on npm. You must specify the exact version number and tag when installing the SDK.

También necesitarás configurar tu proyecto para usar webpack con await de nivel superior habilitado. Por ejemplo, tu configuración debe extender esta configuración base:

module.exports = {
experiments: {
topLevelAwait: true
}
};

Una vez que hayas instalado el SDK de Realm JS con soporte para WebAssembly y configurado tu aplicación, puedes utilizar el SDK para compilar aplicaciones web en tiempo real con Realm y Atlas Device Sync.

The examples in this section show how to work with Realm in your app.

Tip

If you're writing a React application, consider using the @realm/react package. It includes pre-built hooks and components that let you natively integrate Realm with React applications.

Importa el reino en la parte superior de tus archivos de origen donde interactúas con la base de datos:

import Realm, { App } from "realm";

Device Sync uses Atlas App Services to manage authentication and sync data between devices. To use Device Sync from your web app, you must connect to an App Services App that has Device Sync enabled.

You connect to an App using its client App ID. To learn how to get it, see Find Your App ID.

const app = new App({ id: "<your-app-id>" });

Para autenticar a un usuario, llama al método App.logIn() en tu instancia de aplicación. Puedes iniciar sesión con cualquier proveedor de autenticación. Para obtener más ejemplos, consulta Autenticar a un usuario.

const credentials = Realm.Credentials.anonymous();
await app.logIn(credentials);

Realm usa objetos nativos de JavaScript para modelar los datos de tu aplicación. Defines tipos de objetos donde todos los objetos de un tipo dado comparten un esquema que controla el contenido del objeto.

To define a Realm object type, create a schema object that specifies the type's name and properties. The type name must be unique among object types in a realm.

const TaskSchema = {
name: "Task",
properties: {
_id: "int",
name: "string",
status: "string?",
owner_id: "string?",
},
primaryKey: "_id",
};

To open a synced realm, call Realm.open() with a configuration object that specifies the realm's schema and includes a sync configuration object. The sync configuration should specify the authenticated user and define initial subscriptions that control which data is synced:

const realm = await Realm.open({
schema: [TaskSchema],
sync: {
user: app.currentUser,
flexible: true,
// Define initial subscriptions to start syncing data as soon as the
// realm is opened.
initialSubscriptions: {
update: (subs, realm) => {
subs.add(
// Get objects that match your object model, then filter them by
// the `owner_id` queryable field
realm.objects(Task).filtered(`owner_id == "${anonymousUser.id}"`)
);
},
},
},
});

To open a local, in-memory realm that does not sync, call Realm.open() with a local realm configuration object:

const realm = await Realm.open({
schema: [TaskSchema]
});

Once you have opened a realm, you can create, modify, and delete objects in it. All write operations must occur within a Realm.write() transaction block.

const allTasks = realm.objects(Task);
// Add a couple of Tasks in a single, atomic transaction.
realm.write(() => {
realm.create(Task, {
_id: 1,
name: "go grocery shopping",
status: "Open",
});
realm.create(Task, {
_id: 2,
name: "go exercise",
status: "Open",
});
});
const task1 = allTasks.find((task) => task._id == 1);
const task2 = allTasks.find((task) => task._id == 2);
realm.write(() => {
// Modify an object.
task1!.status = "InProgress";
// Delete an object.
realm.delete(task2);
});

Puedes query objetos en un realm usando el método Realm.objects(). Las consultas deben especificar el tipo de objeto Realm a consultar. Opcionalmente, puedes filtrar y ordenar los resultados de una query utilizando una API de cadena de métodos fluida.

// Query for specific obect using primary key.
const specificTask = realm.objectForPrimaryKey(Task, 0);
// Query realm for all instances of the "Task" type.
const tasks = realm.objects(Task);
// Filter for all tasks with a status of "Open".
const openTasks = tasks.filtered("status = 'Open'");
// Sort tasks by name in ascending order.
const tasksByName = tasks.sorted("name");

Call the Realm.close() method when done with a realm instance to avoid memory leaks.

// Close the realm.
realm.close();

Device Sync on the browser is currently subject to the following limitations:

  • No persistence: The Realm JS Web SDK does not persist Device Sync data to disk. All local data is stored in memory and will be lost when the browser tab is closed or refreshed.

  • No worker threads: You must perform all Realm operations on the main thread. You cannot open or work with a realm in a web worker thread.

  • No hay cifrado en reposo: El Realm JS Web SDK almacena todos los datos locales en reposo sin cifrar en memoria. Los datos en tránsito entre el navegador y el servidor Device Sync están cifrados sobre HTTPS.

Next

Bienvenido a la Docs de Atlas Device SDK