Category: Category: Code

Stimulus

Stimulus is a JavaScript framework with modest ambitions. It doesn’t seek to take over your entire front-end—in fact, it’s not concerned with rendering HTML at all. Instead, it’s designed to augment your HTML with just enough behavior to make it shine. Stimulus pairs beautifully with Turbolinks to provide a complete solution for fast, compelling applications with a minimal amount of effort. modest JavaScript framework for the HTML you already have.

I’ve been playing with Stimulus since it was released, and it’s interesting. I can see this being a good answer for stuff like WordPress themes that are designed to be server side but, like any site, could benefit from client-side JavaScript enhancements.

JavaScript for People Who Hate JavaScript

Zach Holman:

I have a long history with JavaScript, dating back to the glory days of the most perfect technology ever to have graced computers: DHTML.

DHTML was totally rad, like how the Budweiser frogs were rad. In the late 90’s you really couldn’t do much of anything on the web except add 88×31 buttons and build with 1×1.gif spacer tricks. But then Dynamic HTML came out in IE4 and a whole world of hover animations, mouse pointer effects, and pretty much nothing else were possible. It was really cool.

Then I did a bunch of other JavaScript from time to time. Everything was pretty terrible until jQuery and Mootools and a slew of other frameworks finally came out in the mid-2000s. That make things almost tolerable for awhile.

Then I started working at GitHub, and my JavaScript experience basically degraded to slinging together some horrific string concatenation and then pushing a pull request, making sure to CC the @github/js team so they would fix everything for me.

Suffice to say, I’ve hated JavaScript for quite some time. But now I’m building a hip new calendar called During, it made a lot of sense to get back into this crappy frontend junk, since a calendar is one of them client-side-heavy apps your parents warned you about growing up.

You know what’s fucked up? I’m kind of loving JavaScript now. I think 2017 is finally the year of “JavaScript on the Desktop”, where “DESKTOP” is an acronym for Developers Enjoy javascript now even though they thought it Sucked compared To Other Programming languages before. (I’m really shit at abbreviations, sorry.)

[..]

Anyway, I’m pretty excited about all this stuff, which is a fun feeling. Hasn’t really been since Rails 0.10 since I’ve been this jazzed up about specific tools in programming. And that’s really cool. Being a novice again — even if it’s for a language I first tried, in some form, almost two decades ago — is a really eye-opening, frustrating, and exciting experience. A+ would learn JavaScript again in 2037.

I’ve been using JavaScript since 1998, I can relate to what Zach’s saying here.

I never left JavaScript though and continued using it throughout the years on both server and client side, especially use it heavily with Flybase, but with React and other technologies out now, it’s gotten to be so much more powerful.

When it comes to JavaScript, this is an exciting year for it.

Using Yarn with Docker

Chromebook Flip

Martino Fornasa:

Facebook recently released Yarn, a new Node.js package manager built on top of the npm registry, massively reducing install times and shipping a deterministic build out of the box.

Determinism has always been a problem with npm, and solutions like npm shrinkwrap are not working well. This makes hard to use a npm-based system for multiple developers and on continuous integration. Also, npm slowness in case of complex package.json files causes long build times, representing a serious blocker when using Docker for local development.

This article discuss how to use Yarn with Docker for Node.js development and deployment.

Yarn is pretty powerful, and combining it with Docker to help make builds smoother makes it even more useful.

Yarn: A new package manager for JavaScript

In the JavaScript community, engineers share hundreds of thousands of pieces of code so we can avoid rewriting basic components, libraries, or frameworks of our own. Each piece of code may in turn depend on other pieces of code, and these dependencies are managed by package managers. The most popular JavaScript package manager is the npm client, which provides access to more than 300,000 packages in the npm registry. More than 5 million engineers use the npm registry, which sees up to 5 billion downloads every month.

We’ve used the npm client successfully at Facebook for years, but as the size of our codebase and the number of engineers grew, we ran into problems with consistency, security, and performance. After trying to solve for each issue as it came up, we set out to build a new solution to help us manage our dependencies more reliably. The product of that work is called Yarn — a fast, reliable, and secure alternative npm client.

We’re pleased to announce the open source release of Yarn, a collaboration with Exponent, Google, and Tilde. With Yarn, engineers still have access to the npm registry, but can install packages more quickly and manage dependencies consistently across machines or in secure offline environments. Yarn enables engineers to move faster and with confidence when using shared code so they can focus on what matters — building new products and features.

You can try yarn right now:

npm install -g yarn

The yarn CLI replaces npm in your development workflow, either with a matching command or a new, similar command:

npm install → yarn

With no arguments, the yarn command will read your package.json, fetch packages from the npm registry, and populate your node_modules folder. It is equivalent to running npm install.

npm install --save <name>yarn add <name>

They’ve removed the “invisible dependency” behavior of npm install <name> and split the command. Running yarn add <name> is equivalent to running npm install --save <name>.

How One Developer Broke Node, Babel, and Thousands of Projects

Chris Williams:

A couple of hours ago, Azer Koçulu unpublished more than 250 of his modules from NPM, which is a popular package manager used by JavaScript projects to install dependencies.

Koçulu yanked his source code because, we’re told, one of the modules was called Kik and that apparently attracted the attention of lawyers representing the instant-messaging app of the same name.

[…]

Unfortunately, one of those dependencies was left-pad. The code is below. It pads out the lefthand-side of strings with zeroes or spaces. And thousands of projects including Node and Babel relied on it.

Azer Koçulu ( via Erik Aybar ):

When I started coding Kik, didn’t know there is a company with same name. And I didn’t want to let a company force me to change the name of it. After I refused them, they reached NPM’s support emphasizing their lawyer power in every single e-mail CC’ing me.

[…]

I’m apologize from you if your stuff just got broken due to this. You can either point your dependency to repo directly (azer/dependency) or if you volunteer to take ownership of any module in my Github, I’ll happily transfer the ownership

Adding Push Notifications to your Parse Server App

I was originally going to write about how to use node.js to enable push notifications, but the latest version of Parse Server now includes basic push notification support using Google Cloud Messaging (GCM) for Android devices and Apple Push Notification Service (APNS) for iOS devices.

Instead, I decided to write about how to enable the built-in push notifications in your Parse Server apps using the updated service.

There are already guides out there on this, but I wanted to put as much information as I could in one place, rather than clicking through to various sources.


Getting Started

This post assumes you previously set up a Parse Server install on Heroku, so some steps will make more sense if you’ve followed that tutorial as well.

To get started, you’ll need your credentials to both GCM and APNS in order to send push notifications to iOS and Android devices.

Preparing your APNS (iOS) credentials

Preparing your Apple Push Notification Service credentials is actually the longest, most detailed part of this post. There are a few steps to follow so I’ll keep them as quick and as short as I can (by the way, if your app is Android only, then you can skip this step obviously):

  1. Log in to the Apple Developer Member Center and click on identifiers under iOS Apps and locate your application in the list.
  2. If you haven’t registered an App Id yet, then click the + symbol and fill out the form, _make sure you check the Push Notifications checkbox.
  3. Click Settings or Edit to continue.
  4. Choose either the Development or Production certificate option and click Create Certificate.
  5. Follow the instructions in the Add iOS Certificate Assistant and click continue.
  6. Using the Certificate Signing request that was just created, generate the APNS Push SSL certificate.
  7. When the Download button appears, you can download your certificate(s). you may need to reload the page for this to update.
  8. Open the download certificate, this will open in the Keychain Access app.
  9. You should see your certificate under My Certificates. If you don’t then check Certificates and it may be there instead.
  10. The final step is to export your certificate as a .p12 file.
    1. Select the certificate that was just added to Keychain Access and select File -> Export Items... from the menu. _Make sure you have select My Certificates from the category menu on the lower left-hand side, if it’s not highlighted then you will not be able to export the certificate as a .p12 file.
    2. When saving the file, use the Personal Information Exchange (.p12) format.
    3. Create a folder in your parse server app called certs and copy the file there.

Ok, you’ve got your .p12 file, we’ll use this shortly to configure push notifications, now onto setting up your GCM credentials.

Preparing your GCM (Android) credentials

Google Cloud Messages is a lot easier to configure than APNS was (by the way, if your app is iOS only then you can skip this step obviously):

  1. Enable GCM for your Android project in the Google Developer Console. This will give you your GCM sender ID, which is your project number. The project number should be a large integer like 129437206252.
  2. Go to the Google developer credentials page, and create a new API key. This API key is your GCM API key.

Configuring Your Parse Server App to Push

Now that we’ve gotten our credentials, we need to update our app to use them.

Let’s look at the config we used in our last post about Parse Server:

var api = new ParseServer({
    databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
    cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
    appId: 'MYAPPID',
    clientKey: 'myclientKey',
    masterKey: 'myMasterKey'
});

First, make sure you run npm install --save parse-server@latest to update your app to the latest version of Parse Server.

Also, you will need to make sure you set the masterKey as that is necessary for sending push notifications from your app via API calls.

Ok, let’s add the new push configuration:

var api = new ParseServer({
    databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
    cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
    appId: 'MYAPPID',
    clientKey: 'myclientKey',
    masterKey: 'myMasterKey',
    push: {
        android: {
            senderId: '', // The Sender ID of GCM
            apiKey: '' // The Server API Key of GCM
        },
        ios: {
            pfx: 'certs/mycert.p12', // the path and filename to the .p12 file you exported earlier.
            cert: '', // If not using the .p12 format, the path to the certificate PEM to load from disk
            bundleId: '', // The bundle identifier associated with your app
            key: '', // If not using the .p12 format, the path to the private key PEM to load from disk
            production: true // Specifies which environment to connect to: Production (if true) or Sandbox
        }
    }
});

Configuring Your Parse Apps to use Parse Server

To update your iOS and / or Android apps to use Parse Server instead of Parse, all you have to do is change the server URL to your installation.

Make sure you update to the latest versions of the SDKs so that you have support for Parse Server.

For example, if you followed the previous post about installing Parse Server on Heroku, then you would point your apps to use: https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com where NAME_OF_YOUR_HEROKU_APP is the name of your heroku app you created.

Configuring your iOS apps

[Parse initializeWithConfiguration:[ParseClientConfiguration configurationWithBlock:^(id<ParseMutableClientConfiguration> configuration) {
    ...
    configuration.applicationId = @"MYAPPID";
    configuration.clientKey = @"myclientKey";
    configuration.server = @"https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com/parse";
    ...
}]];

Configuring your Android apps

Parse.initialize(new Parse.Configuration.Builder(myContext)
    .applicationId("MYAPPID")
    .clientKey("myclientKey")
    .server("https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com/parse")
    ...
    .build()
);

You should also update your app so that it registers for GCM with both Parse’s GCM sender ID and your app’s GCM sender ID. To do this, specify the additional GCM sender ID with the following <meta-data> tag as a child of the <application> element in your app’s AndroidManifest.xml.

For example:

<meta-data
    android:name="com.parse.push.gcm_sender_id"
    android:value="id:YOUR_SENDER_ID" />;

Viewing Installations

Once you’ve configured and updated your apps, you’ll be able to see installations using this curl command:

curl -X GET \
    -H "X-Parse-Application-Id: MYAPPID" \
    -H "X-Parse-Master-Key: myMasterKey" \
    https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com/parse/installations

This will show you how many people have your app installed.

Sending Push Notifications

I know, this was the entire reason you read this far, you want to know how to send push notifications correct? I thought so.

Currently, Parse Server can only send push notifications using API requests with your master key. So, for example:

curl -X POST \
    -H "X-Parse-Application-Id: MYAPPID" \
    -H "X-Parse-Master-Key: myMasterKey" \
    -H "Content-Type: application/json" \
    -d '{
        "where": {
            "deviceType": { "$in": [ "ios",  "android"  ]  }
        },
        "data": {
            "title": "Ant-man",
            "alert": "This is awesome. It is awesome."
        }
    }' \
    https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com/parse/push

Will send a push notification to all registered ios or android devices. Push notifications are formatted as title and alert with alert being the actual message.

Push notifications can also be sent from cloud code:

Parse.Push.send({
    where: {
        "deviceType": { "$in": [ "ios",  "android"  ]  }
    },
    data: {
        "title": "Ant-man",
        "alert": "This is awesome. It is awesome."
    }
}, { useMasterKey: true });

You can now do push notifications to your iOS and Android apps!


Closing Out

Hopefully, this guide will be useful for seeing how to add push notifications to your Parse Server apps. Parse Server is shaping up to be a handy utility so it’s fun to look at the various pieces of it.

In a future post, I’ll show you how to integrate a proper job queue which can then take trigger notifications based on certain criteria, such as a new message notification in a chat room that a user has subscribed to, for example.

Getting Started with Parse Server, Heroku and MongoLabs

Last week, Parse announced they would be shutting down their hosting by January 28th 2017, and like just about every other developer out there, I immediately started playing around with their open sourced Parse Server, and setting it up on Heroku.

For the record, I actually host most of my apps on Flybase (for data), Github Pages or S3 (for frontend) and Heroku for quick node.js apps. I also use Digital Ocean or AWS EC2 for other hosting, but I wanted to demonstrate how to quickly host Parse Server on Heroku first, I’ll show how to set Parse Server up on Digital Ocean and AWS EC2 later in other posts.

Parse Server is actually a pretty nicely written library, and I’ve even forked it to include Flybase support instead of Mongo, as well as having a version that supports multiple apps in one install, but today we’ll look at simply getting Parse Server running on Heroku.


Some Background

Until this week, if you were a Parse user, then you did not need to know how your client side code interacted with your Parse database, and even now, you just need a vague understanding of how it works.

But, there is a lot happening behind the scenes when you host your own Parse Server. So, now that you are going to be hosting it yourself, you should understand how some of it works.

First of all, most of the more difficult work is handled inside the Client side library, and then sent to the server side code as HTTP requests. None of this changes, the only change is where you talk to Parse rather than how you talk to Parse.

That means that all you have to keep in mind when explaining how your self-hosted Parse Server works will be these three sections:

  1. Client code from which you make requests to the server
  2. Server-side code that receives and processes these requests
  3. A Database where the server-side code stores and retrieves data from.

Previously, Parse took care of all of this, but now, we have to setup our mongo database and web server. Luckily, Heroku and Mongolabs work together nicely and almost automatically in this process.

Let’s get started already!

First, You will need to create an account with Heroku, so go create one now if you haven’t already.

Then you’ll need to download the latest version of the Heroku tool-belt here. Once the download has finished you will be able to use heroku commands from the command line. (You’ll see why you want to do this in step 3)

1. Push the button

In your browser, go to: https://github.com/ParsePlatform/parse-server-example, this is a sample node.js app that uses express.js and parse server to

You’ll see a purple button here that says Deploy to heroku.

Press it, press it right now.

2. Prepare the app with Heroku

Heroku’s one button deploys are handy for creating a new app, when you clicked the button in step 1, it took you to a page inside Heroku that asked you to name your app, give it a nice random name, or Heroku will name it for you.

MongoLab was also auto-selected as a necessary add-on, so that’s taken care of for you.

Further down the page, it will give you a list of options:

  1. Keep /parse as your PARSE_MOUNT.
  2. Enter any name you want for APP_ID.
  3. Enter any key you want for the MASTER_KEY.

Now press the deploy for free button, and wait a few minutes.

Once done, you can enter your parse server app by the https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com/parse, if you see a message that says:

I dream of being a web site.

This is placeholder text, and tells you it worked.

3. Modifying your parse server

From the terminal, you want to use the Heroku toolbelt I mentioned before step 1 to download your Heroku’d Parse server and make changes.

Login into heroku using the Heroku toolbelt:

heroku login

Finally, you can clone your new heroku app:

heroku git:clone -a MYPARSEAPPNAME

This will download your parse server app to your local computer inside a folder called whatever you named your heroku app. Replace MYPARSEAPPNAME with the name of your app on Heroku.

If you’ve worked with Parse at all before, then you’re already familiar with having to add a clientKey and appId into the initialization of your client code, to allow your app to communicate with Parse.

Now however, you need to set these keys both in your client code and in the server code.

Open up index.js and set both the clientKey, and appId, to whatever you want

var api = new ParseServer({
  databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
  cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
  appId: 'MYAPPID',
  clientKey: 'myclientKey',
  masterKey: 'myMasterKey'
});

You will then need to go into the initialization block of your code, and set a matching appId.

On your client side, the only code change you’ll need to make is to specify your new server address. This is the address of your Heroku app that hosts your server side code. You can find it in the settings of your app on your Heroku Dashboard. It is just a URL of the form

https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com/parse

Your client code would now look something like this (for javascript):

Parse.initialize('APP_ID', 'CLIENT_KEY');
Parse.serverURL = 'https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com/parse';
var Test = Parse.Object.extend('TestObject');
var test = new Test();
test.save({'animal': true, 'type': 'dog'},{
    success: function () {
        console.log('success');
    },error: function() {
        console.log('error');
    }
});

The final step is to update your Heroku app, since you changed the appId and added a clientKey.

To do that, run these three commands in the terminal:

$ git add --all .
$ git commit -m "My first commit"
$ git push heroku master

When you change code locally, it isn’t updated on Heroku automatically, so you have to run those three commands to:

  1. Add any new files
  2. Commit all changed, added or removed files so the server knows what changed
  3. Upload the changes to Heroku

Also, where you see My first commit, it helps to update that to reflect any changes you’ve made.

4. FINISHED

You can now use your client side Parse code just as you always did, and works as it did before.

Now instead of connecting to a Parse run server, your client code is connecting directly to your Heroku app, which saves all your data in your MongoDB database.

Your queries all work the same as before.

About Cloud Code

you may have noticed this line:

  cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',

This tells your server where your cloud code is located. Cloud code is a feature from Parse that serves as short functions that you can call quickly via HTTP requests such as this one:

curl -X POST \
    -H "X-Parse-Application-Id: myAppId" \
    -H "Content-Type: application/json" \
    -d '{}' \
    https://NAME_OF_YOUR_HEROKU_APP.herokuapp.com/parse/functions/hello

When you migrate from Parse to a self-hosted Parse Server, you can also move over any cloud code you’ve set up so that you just call it when you want to work with it.

The default, included cloud code function is:

Parse.Cloud.define('hello', function(req, res) {
    res.success('Hi');
});

Which means when you make the HTTP request above, you get a return of Hi, where hello is the name of the function you created. You can have as many function as you want, and they all serve different purposes.


It is worth mentioning that several features that made Parse really useful, will not be available in your parse server right away.

The biggest feature that is missing is Push Notifications. But as it happens, it’s pretty easy to add Push Notification support to node.js, and I’ll cover in a later tutorial just how to add Push to your new Parse Server.

Background jobs was another feature missing, but you can look at queue systems or cron jobs to replace them easily. I also plan to write about migrated background jobs to a queued jobs setup.

I also recommend installing the free New Relic add-on inside your heroku app for handy analytics.

Is Heroku really free?

Yes and no, when you first start out, it’s free, but when you are ready to actually use your Parse Server apps then you’ll want to look at the $7 hobby plan at least, the reason for this is because free heroku apps are required to sleep after 30 minutes of inactivity and must sleep for 6 hours in a 24 hour period. This is fine for development, but when ready to actually make use of it, you want to upgrade to the hobby plan for starters.

As I introduce you to posts about deploying Parse Server to other setups such as Digital Ocean and Amazon’s AWS instances, you’ll get a feel for which pricing plans you prefer.

Still Confused?

If you have questions about Parse Server, setting up push notifications, moving your data from Parse to MongoDB or Flybase, then just feel free to get in touch at anytime and I’ll be happy to answer any questions or lend a hand or two.