Database for server in Redux

In the previous lesson we installed msw, which will help us simulate the work of our application with the server. And to start we would like to load upon startup of the application the data already existing on the server.

Let's open our product application, and in it the file server.js. Here we already have a couple of lines of code from the previous lesson.

And the first thing we should ask ourselves: where is data usually stored? Yes, of course in a database, we will answer without thinking. Therefore let's use another cool tool, which will allow us to create a model of our data, and also make it as if we are working with a real SQL database.

The tool that will help us with this - is the library @mswjs/data. To install it, type in the terminal the following command:

terminalnpm install @mswjs/data --save-dev

Now import in the file server.js the things we need:

api/server.jsimport { factory, oneOf, manyOf, primaryKey } from '@mswjs/data'

And let's create our improvised database. For this we will use the function factory. We will do this below after the import lines and before exporting the worker:

api/server.jsexport const db = factory({})

And what data will we store in it? From the server we should receive products, sellers and user reactions. So in our database we must create three models that factory accepts as objects:

api/server.jsexport const db = factory({
  product: {},
  seller: {},
  reaction: {},
})

As in a real SQL database, each of our models must have a primary key. Traditionally, we will assign the id field as such, which we will generate with the same nanoid library:

api/server.jsexport const db = factory({
  product: {
    id: primaryKey(nanoid),
  },
  seller: {
    id: primaryKey(nanoid),
  },
  reaction: {
    id: primaryKey(nanoid),
  },
})

Let's not forget to add nanoid in the import lines at the beginning of the file:

api/server.jsimport { nanoid } from '@reduxjs/toolkit'

In the next lesson we will supplement our models with the necessary fields.

Задание 1

Open your student application. Having familiarized yourself with the material of this lesson, install @mswjs/data for your application.

Задание 2

Next, create the database model db using the function factory. Pass it three objects (student, teacher, vote) for your data, similar to how it is shown in the lesson.