Insert Data on the Backend
Next, we’ll add some tasks on the backend so we can use them later.
Code Explanation
- We added the
initApi
option to theremultExpress
configuration. initApi
is an asynchronous function that runs once when the server is loaded and the API is ready. It allows us to perform initial setup tasks for the API.- We use the
repo
function to get the repository for theTask
entity. The lineconst taskRepo = repo(Task)
gets a Repository of typeTask
that we’ll use to perform all CRUD operations relevant toTask
. - The
if ((await taskRepo.count()) === 0)
check ensures that if there are no tasks in the database, we insert a few default tasks to get started. - The
taskRepo.insert([...])
operation inserts an array of tasks into the database if it’s initially empty, providing some sample data to work with.
See That It Works
Click on the Test the API
button in the preview window. You should see a JSON array with the tasks we defined in the result.
Note: While Remult supports many relational and non-relational databases, in this tutorial we start by storing entity data in a backend JSON file stored in the
db
folder for the project. Later in this tutorial, we’ll switch to using SQLite.
Files
Preparing Environment
- Installing dependencies
- Starting http server