Add a database service to the API project
The goal of iteration 008 is to add a database to the project.
- Cloud-native-todo GitHub repo
At this point, it doesn't matter if it is no-SQL, or SQL-based because there are no relationships or transactions. Someone suggested I look at Prisma for my ORM. After some testing, I realized a free Azure SQL database wasn't going to work because, Prisma requires a 2nd database, although only temporarily, for diffing the migrations.
While I'm sure Prisma has its purpose, at this stage of the project, it seems like overkill compared to adding a database and client library I'm more familiar with. A point in the project where boring is good.
Since I'm already on Azure, selecting some flavor of SQL Server or Cosmos DB makes sense if there is a consumption (pay-as-you-go) pricing tier (SKU) which is free-ish for such as small project. Mongoose and the Cosmos DB API for MongoDB are expedient choices given the wealth of documentation for both for TypeScript/JavaScript.
Add a MongoDB container to the development environment
All the local services are managed by Docker compose for local development where possible. Add the MongoDB container so development and testing don't incur any pay-as-you-go costs.
version: "3"
services:
api-todo:
build:
context: ./api-todo
ports:
- "3000:3000"
depends_on:
- mongodb
client-todo:
build:
context: ./client-todo
environment:
VITE_USE_LOCAL_API: "true"
VITE_API_URL: http://localhost:3000
ports:
- "80:80"
depends_on:
- api-todo
mongodb:
image: mongo:5.0
restart: always
environment:
- MONGO_INITDB_ROOT_USERNAME=mongo
- MONGO_INITDB_ROOT_PASSWORD=MongoPass
ports:
- "27017:27017"
volumes:
- ./mongodata:/data/db
volumes:
mongodata:
Start the service in a separate terminal with:
docker compose up mongodb
I stole this idea from the Contoso Real Estate project which has a wealth of development environment configuration for you to use.
Now that the database is running, add the MongoDB viewer.
Visual Studio Code extension for MongoDB
Make sure you add the MongoDB viewer extension to the development environment, in the devcontainer.json.
"customizations": {
"vscode": {
"extensions": [
...other extensions,
"mongodb.mongodb-vscode",
]
}
},
You can add a connection with a connection string so this can be used for both local and cloud databases.
TODO shape
The shape of the TODO prior to this iteration was:
{
id: 123
title: 'Get Milk'
}
Update the shape to allow for data shape growth:
{
id: '65ad9ad0769c2853d2804f3f',
title: 'Get Milk',
description: 'the oaty kind',
createdAt: '2024-01-21T22:29:36.849Z',
updatedAt: ''
}
The title and description should have a max size to help the UI.
Install mongoose to API
TypeScript types are already in the package so just install it.
npm install mongoose
The package.json shows "mongoose": "^8.0.4", in the dependencies property.