Skip to content

Commit

Permalink
Merge branch 'master' of github.com:mongodb/docs-realm into docsp-31493
Browse files Browse the repository at this point in the history
  • Loading branch information
MongoCaleb committed Jul 27, 2023
2 parents e12a899 + a3763d2 commit f4e6a6c
Show file tree
Hide file tree
Showing 26 changed files with 688 additions and 158 deletions.
4 changes: 4 additions & 0 deletions config/link_checker_bypass_list.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,9 @@
{
"exclude":"npmjs",
"reason":"always returns a 429 -- \"Too many requests\"."
},
{
"exclude":"medium.com",
"reason":"always returns a 429 -- \"Too many requests\"."
}
]
2 changes: 1 addition & 1 deletion examples/node/v12/jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const config: Config = {
{
displayName: "JavaScript",
moduleFileExtensions: ["js", "mjs"],
testMatch: ["<rootDir>/generatedJs/**/*.test.js"],
testMatch: ["<rootDir>/__tests__/**/*.test.js"],
setupFilesAfterEnv: ["<rootDir>/jestSetup.ts"],
modulePathIgnorePatterns: ["<rootDir>/__tests__/testFiles"],
},
Expand Down
4 changes: 2 additions & 2 deletions examples/node/v12/jestSetup.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { jest } from "@jest/globals";
import Realm from "realm";
// Needed to clear the test state.
import { flags } from "realm"
import { flags } from "realm";
flags.ALLOW_CLEAR_TEST_STATE = true;

jest.setTimeout(10000);
Expand All @@ -16,4 +16,4 @@ global.console = {
global.beforeEach(() => {
// Close and remove all realms in the default directory.
Realm.clearTestState();
})
});
4 changes: 3 additions & 1 deletion examples/node/v12/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
"main": "index.js",
"type": "module",
"scripts": {
"test": "jest --runInBand --detectOpenHandles --forceExit",
"posttest": "npm run delete-realm-files",
"test:js": "jest --selectProjects JavaScript --runInBand --detectOpenHandles --forceExit; npm run delete-realm-files",
"test:ts": "NODE_OPTIONS=--experimental-vm-modules jest --selectProjects TypeScript --runInBand --detectOpenHandles --forceExit; npm run delete-realm-files",
"delete-realm-files": "rm -rf *realm.lock *.realm *realm.note *realm.management mongodb-realm *.realm.fresh.lock realm-files myrealm"
},
"author": "",
"author": "MongoDB Realm Docs Team",
"license": "ISC",
"dependencies": {
"fs-extra": "^11.1.1",
Expand Down
26 changes: 16 additions & 10 deletions examples/node/v12/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,29 +23,35 @@ This project defines two test suites, one each for JavaScript and TypeScript,
implemented as Jest projects. To test either JS or TS test suite, run one of the
following:

**JavaScript**
**All JavaScript tests**

```bash
npm run test:js
```

**TypeScript**
**All TypeScript tests**

```bash
npm run test:ts
```

**Single test file**

```bash
npm test -- <fileNameWithExtension>
```

### Understand the Project Structure

The following diagram shows the key items in the project directory:

| Path | Description |
| ------------------ | --------------------------------------------------------------------------------------- |
| `__tests__/` | Examples, test cases, and supporting source files. Add `.js` & `.ts` files here. |
| `babel.config.js` | Configuration for [Babel](https://babeljs.io/) transpilation. |
| `jest.config.js` | Configuration for the [Jest](https://jestjs.io/) testing framework. |
| `tsconfig.json` | Configuration for the TypeScript compiler. |
| `testSetup.js` | Setup and cleanup for the Jest tests. Runs immediately after Jest loads. |
| Path | Description |
| ----------------- | -------------------------------------------------------------------------------- |
| `__tests__/` | Examples, test cases, and supporting source files. Add `.js` & `.ts` files here. |
| `babel.config.js` | Configuration for [Babel](https://babeljs.io/) transpilation. |
| `jest.config.js` | Configuration for the [Jest](https://jestjs.io/) testing framework. |
| `tsconfig.json` | Configuration for the TypeScript compiler. |
| `testSetup.js` | Setup and cleanup for the Jest tests. Runs immediately after Jest loads. |

## Develop

Expand Down Expand Up @@ -118,7 +124,7 @@ async function myExample() {

### Include Generated Code Examples in the Docs

Generated code is available within any `.txt` or `.rst` file via the
Generated code is available within any `.txt` or `.rst` file via the
`.. literalinclude::` directive.

```restructuredtext
Expand Down
134 changes: 134 additions & 0 deletions examples/react-native/__tests__/js/sync/data-ingest.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import {render, fireEvent, act} from '@testing-library/react-native';
import { Button } from 'react-native';
import React, { useEffect } from 'react';
import Realm from 'realm';
import {AppProvider, UserProvider, createRealmContext, useApp} from '@realm/react'

const app = new Realm.App({ id: "js-flexible-oseso" });
const weatherSensorPrimaryKey = new Realm.BSON.ObjectId();
const APP_ID = 'js-flexible-oseso';
let sensors;

// :snippet-start: data-ingest-object
class WeatherSensor extends Realm.Object{
static schema = {
name: 'WeatherSensor',
// sync WeatherSensor objects one way from your device
// to your Atlas database.
asymmetric: true,
primaryKey: '_id',
properties: {
_id: 'objectId',
deviceId: 'string',
temperatureInFahrenheit: 'int',
barometricPressureInHg: 'float',
windSpeedInMph: 'float',
},
};
}
// :snippet-end:

function LogIn() {
const app = useApp();

useEffect(() => {
app.logIn(Realm.Credentials.anonymous());
}, []);

return <></>;
}

// :snippet-start: open-realm
// Create a configuration object
const realmConfig = { schema: [WeatherSensor] };

// Create a realm context
const {RealmProvider, useRealm, useObject, useQuery} =
createRealmContext(realmConfig);

// Expose a sync realm
function AppWrapperSync() {
return (
<AppProvider id={APP_ID}>
<UserProvider fallback={LogIn}>
<RealmProvider
sync={{
flexible: true,
onError: console.error
}}>
<App />
</RealmProvider>
</UserProvider>
</AppProvider>
);
}
// :snippet-end:

const App = () => {
// Getting access to our opened realm instance
const realm = useRealm();

const handleAddSensor = () => {
realm.write(() => {
realm.create('WeatherSensor', {
_id: weatherSensorPrimaryKey,
deviceId: "WX1278UIT",
temperatureInFahrenheit: 66.7,
barometricPressureInHg: 29.65,
windSpeedInMph: 2,
});
});
}

return (
<Button
title='Add A New Sensor'
onPress={() => handleAddSensor()}
testID='handleAddSensorBtn' // :remove:
/>
)
};

describe('Sync Data Unidirectionally from a Client App', () => {

beforeAll(async () => {
// Close and remove all realms in the default directory.
Realm.clearTestState();

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

afterAll(async () => {
app.currentUser?.logOut;
});

test('Create an Asymmetric Object', async () => {
const {findByTestId} = render(<AppWrapperSync />);

// get the Add Sensor button
const handleAddSensorBtn = await findByTestId('handleAddSensorBtn');

// press the Add Sensor button
await act(() => {
fireEvent.press(handleAddSensorBtn);
})

// Access linked MongoDB collection
const mongodb = app.currentUser?.mongoClient('mongodb-atlas');
sensors = mongodb.db('JSFlexibleSyncDB').collection<WeatherSensor>('WeatherSensor');

// check if the new Sensor object has been created
const newSensor = await sensors.findOne({_id: weatherSensorPrimaryKey});
expect(newSensor._id).toEqual(weatherSensorPrimaryKey);
expect(newSensor.deviceId).toBe("WX1278UIT");

// clean up all documents and ensure they are deleted
await sensors.deleteMany({
deviceId: "WX1278UIT",
});

const numberOfWeatherSensorDocuments = await sensors.count();
expect(numberOfWeatherSensorDocuments).toBe(0);
});
});
146 changes: 146 additions & 0 deletions examples/react-native/__tests__/ts/sync/data-ingest.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import {render, fireEvent, act} from '@testing-library/react-native';
import { Button } from 'react-native';
import React, { useEffect } from 'react';
import {AppProvider, UserProvider, createRealmContext, useApp} from '@realm/react'
import Realm from 'realm';

const app = new Realm.App({ id: "js-flexible-oseso" });
const weatherSensorPrimaryKey = new Realm.BSON.ObjectId();
const APP_ID = 'js-flexible-oseso';
let sensors;

// :snippet-start: data-ingest-object
class WeatherSensor extends Realm.Object<WeatherSensor> {
_id!: Realm.BSON.ObjectId;
deviceId!: string;
temperatureInFahrenheit!: number;
barometricPressureInHg!: number;
windSpeedInMph!: number;

static schema = {
name: 'WeatherSensor',
// sync WeatherSensor objects one way from your device
// to your Atlas database.
asymmetric: true,
primaryKey: '_id',
properties: {
_id: 'objectId',
deviceId: 'string',
temperatureInFahrenheit: 'int',
barometricPressureInHg: 'float',
windSpeedInMph: 'float',
},
};
}
// :snippet-end:

// :snippet-start: anonymous-login
function LogIn() {
const app = useApp();

useEffect(() => {
app.logIn(Realm.Credentials.anonymous());
}, []);

return <></>;
}
// :snippet-end:

// :snippet-start: open-realm
// Create a configuration object
const realmConfig: Realm.Configuration = {
schema: [WeatherSensor],
};

// Create a realm context
const {RealmProvider, useRealm} =
createRealmContext(realmConfig);

// Expose a sync realm
function AppWrapperSync() {
return (
<AppProvider id={APP_ID}>
<UserProvider fallback={LogIn}>
<RealmProvider
sync={{
flexible: true,
onError: console.error
}}>
<App />
</RealmProvider>
</UserProvider>
</AppProvider>
);
}
// :snippet-end:

// :snippet-start: write-data-ingest-object
const App = () => {
// Getting access to our opened realm instance
const realm = useRealm();

const handleAddSensor = () => {
realm.write(() => {
realm.create('WeatherSensor', {
_id: weatherSensorPrimaryKey,
deviceId: "WX1278UIT",
temperatureInFahrenheit: 66.7,
barometricPressureInHg: 29.65,
windSpeedInMph: 2,
});
});
}

return (
<Button
title='Add A New Sensor'
onPress={() => handleAddSensor()}
testID='handleAddSensorBtn' // :remove:
/>
)
};
// :snippet-end:

describe('Sync Data Unidirectionally from a Client App', () => {

beforeAll(async () => {
// Close and remove all realms in the default directory.
Realm.clearTestState();

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

afterAll(async () => {
app.currentUser?.logOut;
});

test('Create an Asymmetric Object', async () => {
const {findByTestId} = render(<AppWrapperSync />);

// get the Add Sensor button
const handleAddSensorBtn = await findByTestId('handleAddSensorBtn');

// press the Add Sensor button
await act(() => {
fireEvent.press(handleAddSensorBtn);
})

// Access linked MongoDB collection
const mongodb = app.currentUser?.mongoClient('mongodb-atlas');
sensors = mongodb!.db('JSFlexibleSyncDB').collection<WeatherSensor>('WeatherSensor');

// check if the new Sensor object has been created
const newSensor = await sensors.findOne({_id: weatherSensorPrimaryKey});
expect(newSensor?._id).toEqual(weatherSensorPrimaryKey);
expect(newSensor!.deviceId).toBe("WX1278UIT");

// clean up all documents and ensure they are deleted
await sensors.deleteMany({
deviceId: "WX1278UIT",
});

const numberOfWeatherSensorDocuments = await sensors.count();
expect(numberOfWeatherSensorDocuments).toBe(0);
});
});
6 changes: 0 additions & 6 deletions node_modules/.package-lock.json

This file was deleted.

Loading

0 comments on commit f4e6a6c

Please sign in to comment.