Introduction
This post introduces the MongoDB Stitch CLI, demonstrating how the Command Line Interface (CLI) can be used to export an existing app, continue to develop it locally, and then merge the changes back into Stitch. This workflow allows automation, enables collaboration, and increases productivity.
Introducing MongoDB Stitch
MongoDB Stitch is a serverless platform which accelerates application development with simple, secure access to data and services from the client – getting your apps to market faster while reducing operational costs and effort.
The Stitch serverless platform addresses the challenges faced by the developers of modern applications by providing four services:
- Stitch QueryAnywhere: Exposes the full power of working with documents in MongoDB and the MongoDB query language, directly from your web and mobile application frontend code. A powerful rules engine lets developers declare fine-grained security policies.
- Stitch Functions: Allows developers to run simple JavaScript functions in Stitch’s serverless environment, making it easy to create secure APIs or to build integrations with microservices and server-side logic. Enables integration with popular cloud services such as Slack and Twilio, enriching your apps with a single Stitch method call.
- Stitch Triggers: Real-time notifications that launch functions in response to changes in the database. The functions can make further database changes, push data to other places, or interact with users – such as through push notifications, text messages, or emails.
- Stitch Mobile Sync: Automatically synchronizes data between documents held locally in MongoDB Mobile and the backend database. MongoDB Mobile allows mobile developers to use the full power of MongoDB locally. Stitch Mobile Sync ensures that data is kept up to date across phones and all other clients in real time.
The Sitch CLI
Stitch has an intuitive UI to create and maintain your apps, but you also have the option of using the Stitch CLI. The stitch-cli
is the key to automating workflows with Stitch (it also lets you develop code inside your favorite editor). The CLI provides functions for authenticating Stitch users, importing local application directories, and exporting applications from the MongoDB Stitch service.
With the import
& export
commands in the Stitch CLI, you can:
- Develop Stitch applications using your favorite desktop editor and import them into Stitch
- Export existing applications to a local directory. From there you can:
- Add the files to source control (e.g., GitHub)
- Make changes to the application code and configuration files, before merging those changes back into your Stitch app
- Let other developers review and contribute code
- Easily share custom services and functions between Stitch apps
- Push code from development environments, to QA, and onto production.
stitch-cli
currently includes 5 commands:
login
: Log in using an Atlas API Keylogout
: Deauthenticate as an administratorwhoami
: Display Current User Infoexport
: Export a stitch application to a local directoryimport
: Import and deploy a stitch application from a local directory
While MongoDB Stitch lets you create complex applications, it also simplifies development by mapping your apps to standard JSON and JavaScript files and structures in a way that's easy to navigate.
An exported application is made up of a hierarchy of directories and files:
*.json
: Files containing configuration data*.js
: Files containing JavaScript code
This is an example hierarchy for a Stitch IoT service that works with the backend MongoDB Atlas database and the REST APIs of 2 other cloud services – IFTTT and DarkSky.net:
impTemp
├── auth_providers
│ ├── anon-user.json
│ └── api-key.json
├── functions
│ ├── Imp_Write
│ │ ├── config.json
│ │ └── source.js
│ ├── TempTimeline
│ │ ├── config.json
│ │ └── source.js
│ └── controlHumidity
│ ├── config.json
│ └── source.js
├── services
│ ├── IFTTT
│ │ ├── config.json
│ │ └── rules
│ │ └── IFTTT.json
│ ├── darksky
│ │ ├── config.json
│ │ └── rules
│ │ └── darkSkyGET.json
│ └── mongodb-atlas
│ ├── config.json
│ └── rules
│ └── Imp.TempData.json
├── stitch.json
└── values
├── DarkSkyKey.json
├── DeviceLocation.json
├── MakerIFTTKey.json
├── maxHumidity.json
└── minTemp.json
Installing stitch-cli
The simplest way is to install stitch-cli
is as an NPM module:
npm install -g mongodb-stitch-cli
Logging into the Atlas API
Before doing anything else, you need to create an Atlas API key & whitelist your local machine's IP Address, as shown here:
You can now log into the admin API using stitch-cli
, and confirm that you're logged in:
stitch-cli login --username=andrew.morgan --api-key=XXXXXXXX-XXX-4010-97a2-ad7c39d8cfb5
stitch-cli whoami
andrew.morgan [API Key: ********-****-****-****-ad7c39d8cfb5]
Export app, make local edits, and merge changes back into the same Stitch app
I noticed that I'm missing some error handling code in my functions. Rather than editing them all through the Stitch UI, I export the app so that I can work on the code in my favorite browser:
Export the Stitch app to the local file system:
stitch-cli export --app-id=imptemp-sobpa
I then add some extra code to handle cases where the MongoDB insert fails:
exports = function(data){
//Get the current time
var now = new Date();
var darksky = context.services.get("darksky");
var mongodb = context.services.get("mongodb-atlas");
var TempData = mongodb.db("Imp").collection("TempData");
// Fetch the current weather from darksky.net
darksky.get({"url": "https://api.darksky.net/forecast/" +
context.values.get("DarkSkyKey") + '/' +
context.values.get("DeviceLocation") +
"?exclude=minutely,hourly,daily,alerts,flags&units=auto"
}).then(response => {
var darkskyJSON = EJSON.parse(response.body.text()).currently;
var status =
{
"Timestamp": now.getTime(),
"Date": now,
"Readings": data,
"External": darkskyJSON,
};
status.Readings.light = (100*(data.light/65536));
context.functions.execute("controlHumidity", data.temp, data.humid);
TempData.insertOne(status).then(
results => {
console.log("Successfully wrote document to TempData");
},
error => {
console.log("Error writing to TempData colletion: " + error);
});
});
};
I then apply the updates to the Stitch app (the CLI conveniently shows me the delta before I commit the merge):
cd impTemp
stitch-cli import --app-id=imptemp-sobpa --strategy=merge
--- functions/Imp_Write/source.js
+++ functions/Imp_Write/source.js
@@ -28,6 +28,9 @@
TempData.insertOne(status).then(
results => {
console.log("Successfully wrote document to TempData");
+ },
+ error => {
+ console.log("Error writing to TempData collection: " + error);
});
});
};
Please confirm the changes shown above: [y/n]: y
Successfully imported 'imptemp-sobpa'
You can then validate the changes through the UI:
Summary
The Stitch CLI make it easier than ever to work with Stitch code – regardless of whether you’re an advanced user or just beginning. If you've created your first stitch app, try the Stitch CLI to start extending it – all from the comfort of your favorite editor. If not, try importing this example dashboard application.
Sign up for the Stitch free tier and see what you can create!