About the application
The application will have REST services for each of following operations :
- Create user
- Read users
- Update user
- Delete user
For each operation it will query into the database which is created in MongoDB.
Prerequisites
- Deno should be installed and running.
- Local or Remote MongoDB database with a collection like users.
{
"_id": {
"$oid": "5e68a5cdb25ebb404cfeef00"
},
"email": "...........",
"password": "...............",
"username": "........"
}
Create Modules
Let’s start by creating modules for the application one by one.
db.services.ts will have all the methods to perform CRUD operations with database.
- Import MongoClient module import { MongoClient } from "https://deno.land/x/mongo@v0.7.0/mod.ts";
- Connect to database using database URLand fetch the collection (users).
const client = new MongoClient(); const DB_URL = "mongodb://localhost:27017"; const DB = "jobsheduler"; const COLLECTION = "users"; client.connectWithUri(DB_URL); const users = client.database(DB).collection(COLLECTION);
Create methods for all the CRUD operations similar to below method (getAllUsers)
export async function getAllUsers() { const result = await users.find(); return result; }
rest.services.ts This module will have all theREST API services for CRUD operations.
Define all the REST API pathsC- Import Router module.
import { Router } from 'https://deno.land/x/oak/mod.ts';
- Import all the methods of db.services.ts.
import { getAllUsers, addUser, deleteUser, updateUser } from './db.services.ts';
- reate
Start the application
Development part of the application has been completed. Now, it’s time to start the application.
- Open the terminal/command prompt in the app.server.ts location.
- Run the following command :
deno run --unstable --allow-read --allow-write --allow-plugin
--allow-net app.server.ts- You should see the following message on your console which means your application is running.
Before moving to the next step, you must be wondering what are all those arguments used with run command. Let’s understand them first.
--unstable --allow-read --allow-write --allow-plugin
--allow-netunstable is used to allow modules/plugins which are declared unstable currently by Deno.
allow-read and allow-write are used to take permission for reading and writing files, in this case the database collection in MongoDB.
allow-plugin is used to take permission for using plugins, in this case the MongoDB plugin to connect with database.
allow-net is used to take permission for network related operations like server hosting.
Test the application
Finally, it’s time to test the application. Firstly, Make sure your local or remote MongoDB instance is up and running. Now, open the following URL in any web browser and where you should be able to see all users from the collection.
http://localhost:5000/app/users
Comments
Post a Comment