deno and oak with mongoDB and Redis

Luvdeep Katyal
8 min readJun 21, 2020

Now there is a lot of speculations in the world of backend that either deno is going to replace Node.JS , well after my research and study the conclusion that i have reached is clearly ‘NOT FOR NOW’.

deno is definately the future but for now it is not going to murder everyone’s favourite Node.JS.
It is just a new toy in the town for developers and programmers, so just have fun while playing with it.

Jumping on to the introduction about deno which is a secure runtime for JavaScript and as well as TypeScript.
It has been built on V8 engine just as Node.js and in addition Rust, and Tokio.
- deno is by default secure as it doesn’t provide access for files, environment or network unless enabled.
- One of the promising advantage for deno is all the scripts can be bundled into a single JS file and it is browser compatible.

Comparing deno with Node.JS:

- deno has no modules, it doesn’t need the use for npm and package.json as well, so does it restricts the use of third parties and modules, no it doesn’t, it uses modules referenced as URLs or file paths, just simply import these in your code and get ready for their use.
- deno provides different API’s from Node.JS as all of the async actions return a promise.
- deno dropped the use of require() and only imports are allowed.
- An advantageous one deno allows you to use the top-level-await, which can run directly without an asynchronous function.

Installation:

deno works on macOS, Linux, and Windows and it has no external dependencies.

Using Shell (macOS and Linux):

$curl -fsSL https://deno.land/x/install/install.sh | sh

Using PowerShell (Windows):

$iwr https://deno.land/x/install/install.ps1 -useb | iex 

You can also use Scoop and Chocolatey for Windows or even Cargo which can also work for Linux and macOS.
Once installed, run deno --version, if it prints version which is currently 1.1.0 your installation is successfull.
You can also go for a repl with deno just as in Node.JS.

For starting with implementation i am going to use oak, which is a middleware framework for deno’s http server, including a router middleware.
This middleware framework is inspired by Koa and middleware router inspired by @koa/router.
You can also use another server framework for your implementation like Pogo which is an easy-to-use, safe, and expressive framework for writing web servers and applications. It is inspired by hapi.

You will be getting these third-party modules from https://deno.land/x , for mongodb i am using deno_mongo which is a MongoDB database driver developed for deno, based on rust’s official mongodb library package, which includes only a few mongodb queries and not all, these are insertOne, insertMany, find, findOne, updateOne, count, updateMany, deleteOne and deleteMany along with aggregate. With the use of these i am going to perform basic CRUD operations on MongoDb with oak and also storing the data in our Redis , for redis i am using deno-redis.

Structure

I am using a simple structure for implementation, a server file, a router file to include all of my routes, a redis service file which implies my port and host to be used for redis, a database file for connectivity with my database(mongodb), a constant file that contains constant messages and values to be defined and a controller file that contains all of the buisness logic to be executed.

Here it goes in my server file

server.ts

I simply import Application from deno oak,

the Application class is used for wrapping the serve() function from the http package.

- The Application class has two methods namely .use() and .listen()

- Our middleware is added from the .use() method and the .listen() method will start the server and start processing requests
with the registered middleware. Whenever our middleware is called, it is passed as a context.
- context.request contains information about the request and similarly the context.response contains information about the response which is sent to our client.

Similarly import the Router from “https://deno.land/x/oak/mod.ts", into the router file which produces middleware which can be used with an Application to enable routing based on the pathname of the request.

Start your server using:
deno run --allow-read --allow-env --allow-write --unstable --allow-net
--allow-plugin server.ts

Because the plug-in API of Deno is still in an unstable state, the unstable flag needs to be used. Rest of the flags are to allow read ,write and network and use allow env if you are using the .env file for your code.

Now after my server file is ready just make a connection to my MongoDb, import the MongoClient, create a client and with the help of connectWithUri method which takes in your connection url create your database and a collection on which you want to perform your operations.
You must use the dotenv for your implementation and can keep your connection string into your .env file for specific reasons and by importing dotenv/load.ts from deno and using “Deno.env.get(anyVariable)” can use the value of the variable declared into your .env file, here i am just using my localhost so currently i am not following this process.

Now import connect from deno-redis and declare your hostname and port for your redis connection.

In case you do not have redis installed or if you are a newbie to redis get it downloaded from redis.io and install it using the command sudo apt install redis-server.

coming to creating your routes in the router file import Router from oak instanciate a new router and start creating your routes.

deno oak gives your code cleanliness in creating different routes from your router with simplicity.You can also use the routes into your your server file if you have a very short project.

With the very first route i insert a user into my collection using the context request and response, i accept the request in a body and destructuremy request body

Request and body

in the end after my queries and logic i save my data to the database and set the key value into the redis and give my client the desired response using the context

Storing the data in mono, redis and returing the response

Using postman for the request and response of my API’s to see the response, view the request and response for the insertOne endpoint

Request and Response from Postman

Here the insertOne returns “$oid” in case if you are familiar with “_id”, they are same it is merely the representation, internally they are stored in the same way for more information visit: https://docs.mongodb.com/manual/reference/mongodb-extended-json/

HTTP Status Code 201 might be a bit confusing for you all but actually it is represents a new resource being created, it is all upto you and your understanding, you can still go with the status code of 200.

Likewise you can proceed with other requests and response i am just sharing more of the requests and responses of my other API’s.

and of course go ahead with validations in each of the API based on your requirements, just like,

Email to be unique for every document in the collection in insertOneUser Api

2. Get All Users

User Listing

3. Get One User based on its id

For these kinds of retrievals prefer data coming from the redis at first and if your data is not present in redis (flushed or redis server is down)
You can only then query your database you may use this in the case of the userList API as well, like below i did it for a single user retrieval

Get One User function from the controller

4. Update a document from the collection

Update API request and response

In this API, i really missed mongoose and mainly the findOneAndUpdate() as for a single key update i had to query the db again for updated values to be overwritten in redis for the same key, i missed the use of post and pre hooks that could easily replace the whole updated document in my redis after the query being executed.

When you try to run your code with findOneAndUpdate() it gives you an error of Property ‘findOneAndUpdate’ does not exist on type.

Since for now i could not found anything in deno for mongoose schema declaration for our collection i had to bear with it and using primitive ways to set the value of my key in redis.

5. Delete a single user

Response for delete request
deleteOneUser function from the controller

Just update the status and following the backend rules “SOFT” delete the user and use del command to delete the key from redis

That’s all folks, that’s the basics for deno with oak mongodb and redis
I believe you can try yourself for your own base projects with deno and enjoy deno just as Node.JS

Photo by Svyatoslav Romanov on Unsplash

Keep Learning guys Life and Programming both are just about Learning
Keep growing. Please clap and share if you liked the article Thank you for the read. Explore https://deno.land/ for more. Thanks

--

--