Posts tagged NodeJS

In Building Microservices with SenecaJS: Part 1, we finished writing a simple, RESTful microservice for products with hard-coded data. Now it’s time to hook into a real data store and showcase Seneca’s data abstraction layer. In this post, we will be looking at the JSON file store. In the next post, we will swap this out for a MongoDB store.

There are many advantages to using a file store or in-memory store. One of the advantages is the ease of testability since you don’t have to make an actual connection to the data store. You can run your tests on your local machine (in isolation) and you won’t have to worry about the data getting out sync as it maybe if you’re using a shared database.

There is a couple of changes that are needed to use Seneca’s data entity plugin. First, we need to include the dependencies on “seneca-entity” and the type of store we’re interested in using (jsonfile-store). Here is a snippet:

Now we’re ready to start using the file store. But, we don’t have data in our file store yet. So, it’s time to introduce another end-point to our API in which product information can be added (POST’ed).

In the previous snippet, we accessed the ‘products’ collection on the first line. If it doesn’t exist, it will be created with the first save. Then, in our add action/cmd, we saved the record using the save$ method from the entity plugin, capturing the new product information from the request body (assuming it is JSON). We now need to register the end-point by mapping it to our new action. This is done via the web plugin:

In the snippet above, we accessed the ‘products’ collection on the first line. Then, in our getProductById action, we loaded the record using the product id from request parameter. And that’s it. We have a fully functioning service communicating with a real data store. The full project code is listed on GitHub.