Hello World

Chapter 1: How to create a Hello World service for Resgate

Note

This guide describes the RES Protocol using raw JSON calls to NATS with NodeJS examples.

For language specific service libraries, such as for .NET (dotnetcore) and Go (golang), visit those projects.

A Hello World service written for Resgate, using NodeJS, could look like this:

const nats = require('nats').connect('nats://localhost:4222');

nats.subscribe('get.example.model', (req, reply) => {
	nats.publish(reply, JSON.stringify({ result: { model: { message: "Hello, World!" }}}));
});

nats.subscribe('access.example.model', (req, reply) => {
	nats.publish(reply, JSON.stringify({ result: { get: true }}));
});

It serves a single resource, example.model, that contains the data:

{ "message": "Hello, World!" }

The resource can be retrieved through Resgate (running on default settings) with a HTTP GET request:

http://localhost:8080/api/example/model

Or with ResClient over WebSocket:

client.get('example.model').then(model => {
	console.log(model.message);
});

Tip

To run the Hello World service:

npm install nats
node hello-world.js

How to use the guide

Each chapter will describe different aspects of writing services that uses Resgate, with footnote links to the protocol specification. Each guide will come with partial examples written in Javascript, for NodeJS, without using any library made specifically for Resgate and RES services.

But of course, services can be written in any of the languages supported by NATS Server.

If you would rather just create a service without learning how the protocol works, you can look at the list of service libraries.

Note

The Javascript examples are written with newer Javascript syntax (ES6). If you are unfamiliar with keywords such as const or let, these three points will help you out. For browser client examples, it will also be useful to learn about promises first.