Quick Links 🔗

→ MongoDB Realm, GraphQL, React

Setup

Install Realm SDK 😻

npm install realm-web
# for yarn users 
yarn add realm-web

Initialize Realm

  1. Import Realm
  2. Initialize the app using you APP_ID, which can be graped from MongoDB website
  3. Add the requierd functions to work with Realm
  4. Export graphqlUrl and getValidAccessToken(), to use them later in other placeses
// MongoDB Realm
import * as Realm from 'realm-web';

export const APP_ID = '...';
const graphqlUrl = `https://realm.mongodb.com/api/client/v2.0/app/${APP_ID}/graphql`;

// Connect to your MongoDB Realm app
const app = new Realm.App(APP_ID);

// Get a valid Realm user access token to authenticate requests
async function getValidAccessToken(): Promise<string> {
	if (!app.currentUser)
		// If no user is logged in, log in an anonymous user
		await app.logIn(Realm.Credentials.anonymous());
	else
		// The logged in user's access token might be stale,
		// Refreshing custom data also refreshes the access token
		await app.currentUser.refreshCustomData();

	// Get a valid access token for the current user
	localStorage.setItem('token', app.currentUser.accessToken);
	return app.currentUser.accessToken;
}

export {
	graphqlUrl,
	getValidAccessToken
};

Install Apollo 👾

ng add apollo-angular

Connect Realm ↔ Apollo

  1. Add realm graphqlUrl
  2. Add Authorization header to Apollo requests
...

import * as realm from './realm';
const uri = realm.graphqlUrl;

export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
	return {
		link: httpLink.create({
			uri,
			headers: new HttpHeaders().set('Authorization', `Bearer ${localStorage.getItem('token')}`)
		}),
		cache: new InMemoryCache()
	};
}

...

Setup a routes guard 👻

  1. Create the guard