12/27/2021

Vue Storefront Docker

88

# Using native Magento 2 module

  1. Vue Storefront Docker Login
  2. Vue Storefront Docker Portal
  3. What Is Docker Image
  4. Vue Cli Docker
  5. Docker Compose Vue
  6. Vue Storefront Docker Login

There is a native Magento 2 module(opens new window) that synchronizes Magento 2 source data and Vue Storefront data store; Elasticsearch.
Magento 2 VSBridge Indexer(opens new window) has a few advantages. More than anything, it's faster and reliable.

Vue Storefront Built with a PWA and headless approach, using a modern JS stack, Vue Storefront provides shopping experiences like native apps and boosts site performance. Vue Storefront is an open-source frontend for any frontend. It can be hooked with Magento 2, Magento 1, Shopware, Commercetools, BigCommerce, etc. Vue Storefront is a PWA, i.e., it provides shopping experiences. The rest of the config.js entries point out to your vue-storefront-api based Docker and Redis instances, which are required by mage2nosql to work. To make the full import, you should run the following commands (the sequence of commands is important, as, for example, node cli.js categories populates the Redis cache for further use of node cli.

# Using Magento 2 API via OAuth authorization

The tool is using Magento 2 API via OAuth authorization, so you need to prepare Magento Integration access at first. Go to your Magento 2 admin panel and click: System → Integrations.

Click Add New Integration and fill in:

  • Name (whatever)
  • Your password to confirm the changes
  • On the API Permissions tab, check the following resources:
    • Catalog
    • Sales
    • My Account
    • Carts
    • Stores > Settings > Configuration > Inventory Section
    • Stores > Taxes
    • Stores > Attributes > Product
  • Save

In the result, you’ll click Activate and get some OAuth access tokens:

# Integrating Magento 2 with your local instance

# Fast integration

The Magento2 data import is now integrated into vue-storefront-api for simplicity. It's still managed by the mage2vuestorefront(opens new window), added as a dependency to vue-storefront-api.

After setting the config.magento2.api section using yours Magento 2 OAuth credentials:

You can run the following command to execute the full import of all the products, categories, and other important stuff to your Elasticsearch instance:

... or in multistore setup, you can run the same command with specified store-code parameter

# Manual integration

First, you need to install mage2vuestorefront (opens new window):

Now edit the src/config.js file in your mage2vuestorefront directory to set the following section:

As you can see, you can override the defaults by ENV variables as well.

The rest of the config.js entries point out to your vue-storefront-api based Docker and Redis instances, which are required by mage2nosql to work.

Vue Storefront Docker Login

Vue

To make the full import, you should run the following commands (the sequence of commands is important , as, for example, node cli.js categories populates the Redis cache for further use of node cli.js products and so on).

It’s safe to run these commands over and over, as they’re doing upsert operation, so it inserts or updates the existing records.

cli.js has a lot of other modes to be run in—dynamic changes, queue support, etc. You may experiment with them, but remember , the basic sequence for syncing the whole Magento 2 database is like just shown.

# Synchronizing orders and Magento images

As you should have the products and categories already synchronized, you may want to send some orders back to Magento or synchronize the shopping carts in real time.

vue-storefront-api is responsible for this write access to Magento. You may want to edit your conf/local.json within the vue-storefront-api directory to set the OAuth Magento API access (magento2 section):

To allow vue-storefront-api to resize your Magento images, please edit the imgUrl property under magento2 section and add your Magento’s domain to imageable -> whitelist.

NOTE

After changing the config files you need to restart yarn dev

After setting up Magento access, you just need to run the Order2Magento worker, which works on a Redis-based queue to process all the orders made by users.

The code of this script is located here(opens new window) so you can easily check how it’s working.

Starting from Vue Storefront v1.6, now we have a special switch in vue-storefront-api: config.orders.useServerQueue which is set to false by default. With this option disabled, the order_2_magento process is no longer needed, as the incoming orders are directly send to Magento 2. If it's set to true, the old behavior of the server-based Redis queues used to stack the orders first is being used.

# Synchronizing shopping carts

By default, shopping carts are not synchronized in real-time , only after the order is placed, Magento 2 cart is created, etc.

This was limiting behavior because you need to keep the user cart current all the time to get Magento 2 shopping-cart promotion rules into action .

We have an option for that! If you have the Magento 2 API configured within the vue-storefront-api, you just need to go to vue-storefront/conf/local.json and add

to cart section. Please check the default config for reference(opens new window).

Nest.js is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. This definition, although very accurate, doesn't indicate when to use Nest.js in the next project, and I'll try to throw some light on that issue.

Nest.js can be seen as Angular on the backend (as one of my friends called it) as it provides a plethora of useful features, and - just as Angular can be a bit overwhelming at first glance. To avoid overloading with the info, I'll skip to the most crucial ones from my point of view:

  • Built with TypeScript
  • Many technologies supported out of the box (GraphQL, Redis, Elasticsearch, TypeORM, microservices, CQRS…)
  • Built with Node.js and Supports both Express.js and Fastify
  • Dependency Injection
  • Architecture (!)

Core Concepts of Nest.js

If you are not yet familiar with Nest.js there are three basic concepts that you will be working on all the time; `Modules`, `Controllers`, and `Services`.

Modules

Modules encapsulate logic into reusable pieces of code (components).

Controllers

Used to handle REST operations (HTTP methods).

Services

Services are used to handle logic and functionality. Service methods are called from within a controller.

Microservices

There is a great article series by Chris Richardson regarding Microservices available on https://microservices.io/. Make sure to read it first if you are not familiar with this concept.

Ok, let's jump to the code! You will need two repositories that I have prepared for this tutorial:

Make sure to clone them and install all required dependencies. We will also need a Docker installed on our system and a Database Management Tool of your choice (I am using Table Plus). Also, a Postman would be needed to test endpoints.

Refactoring basic server to microservices

In this section what we will do is we will be converting two basic Nest.js servers to the main server (API Gateway) and microservice (responsible for handling item operations).

If you get lost at some point, inside the repositories there are commits and branches that will help you do the refactor step by step.

Repositories

There are two repositories ready to serve as a simple example and they are very similar Nest.js servers with small differences:

nest-microservice

  • `.env.example` file with environment variables that you would need to copy to `.env` file for the `docker-compose.yml` to work.
  • docker-compose.yml file with configuration of PostgreSQL image to serve our database.
  • required npm packages for the demo to work.

nest-demo:

  • required npm packages for the demo to work.

Both projects are basic Nest.js servers:

If we run these servers using `yarn dev` or `npm run dev` commands we would see in the browser `Hello World`.

Vue Storefront Docker

Now into the actual refactoring

What we will do in this section is we will take the code from the basic server and refactor it to API Gateway and a microservice. If you are not yet familiar with the concept of API Gateway there is a great article about it by Chris Richardson on https://microservices.io/patterns/apigateway.html.

nest-demo:

  • Inside `app.module.ts` we will add a ClientsModule with some option to allow our server to communicate to the microservice using TCP connection.

Inside `app.controller.ts` we will add two new endpoints that would allow us to test both READ and WRITE functionality.

Inside `app.service.ts` we will add two additional methods to handle new endpoints by sending a message pattern and data to the corresponding microservice.

In here we are injecting the `ITEM_MICROSERVICE` client that we have declared in `app.module.ts` in order to later use it in certain methods to send the message.

`send` method accepts two arguments; `messagePattern` in the form of an object, and a `data`.

If you need to pass more than one variable (i.e. `firstName` and `lastName`) create an object out of it and send them in that form as a second argument.

Make sure to remember or copy the value of `messagePattern` because we will need it in that exact form in the microservice to respond to this message.

And that will be it for the `nest-demo` project. Do not run the project yet as the microservice is not ready yet to handle requests.

nest-microservice:

Create an `item.entity.ts` file. It will be used to model our database tables.

In here we are declaring a table with two columns; `id` and `name`.

Vue Storefront Docker Portal

Create an `item.repository.ts` file to be able to work with the entity on the database (create, find, delete, etc).

In here we could create our methods for working with entity but for this tutorial we will only need the default ones provided by `typeorm`.

  • Modify `app.module` to connect to the PostgreSQL Docker container and load `ItemRepository` and `ItemEntity`.

For the real application remember to not use credentials in plain values but use environment variables or/and [@nestjs/config](https://github.com/nestjs/config) package.

Refactor `main.ts` file from basic Nest.js server to Nest.js Microservice.

Refactor `app.controller.ts` to listen to messages rather than HTTP methods (messagePattern from nest-demo will be needed here).

Storefront

Here we are using the messagePattern from nest-demo to react for the messages with certain pattern and we trigger methods inside appService.

Refactor `app.service` to handle the READ and WRITE methods.

What Is Docker Image

In here we are using the injected `itemRepository` to save a new `ItemEntity` or find existing one by id.

Running all API Gateway, Microservice and Database Container

To run all services I would recommend to open two terminal windows or three if you are not using Docker Desktop.

Vue Cli Docker

  1. Run PostgreSQL container by using `docker-compose up` in `nest-microservice` project or by using Docker Desktop.
  2. Run `yarn dev` or `npm run dev` in the `nest-microservice` project to start microservice.
  3. Run `yarn dev` or `npm run dev` in the `nest-demo` project to start API Gateway.

Docker Compose Vue

Testing if everything is working correctly

  1. Connect to your PostgreSQL container with TablePlus using the same credentials that you used for your Nest.js application in the TypeORM module.
  2. Trigger a POST endpoint in Postman to `http://localhost:3000/create` with name of your item in the body
  3. You should see the response in Postman and also a new record in the TablePlus.
  4. To test even further you could also send a GET request to `http://localhost:3000/item/:id` where :id will be 1. And you should see the correct item object that we got from PostgreSQL.

Summary

In less than 10 minutes of this article time we have refactored two basic Nest.js servers to API Gateway and a microservice. Well done!

However, to better understand this topic you would probably need more time but this is a solid introduction to the topic of Microservices in Nest.js.

Useful links

Bonus: Microservice Template

If you are interested in more advanced examples of Nest.js Microservices I have created a Microservice Template that you can use to create your own microservices: https://github.com/otasoft/microservice-template

It consists of:

Vue Storefront Docker Login

  • PostgreSQL Typeorm
  • CQRS
  • Domain Driven Design
  • Event Sourcing
  • Healthchecks
  • Unit tests
  • .env support
  • RabbitMQ Event Bus Connection
  • Dockerfile and docker-compose
  • doc directory
  • Github workflows and issue templates
  • Most Viewed News