NestJs Locking Resource

Abiral Sthapit
2 min readMar 4, 2022

--

In NestJs between two different asynchronous calls, we had to determine if the calls are using the same resource or not, for example, uploading and deleting the resources. Sometime uploading a samefile multiple time consicutively to cause duplicates and deleting a file consicutively to throw a server error as the file being hold by the server for deletion cause major issue if the Frontend request is not properly handled.

Resource Locking is a simple concept where we can lock an async request applying for the same resource before the task is completed. Implementing a resource lock-in NestJs is pretty straightforward, let's take a simple example.

But this is not a good way to lock a resource as the server may not be a single instance and a resource could be anything besides a simple async task, if we are going to use it in an n-tier architecture then this solution will fail miserably.

A simple fix for this would be to create a resource locking mechanism using the database, here I am using Postgres and Prisma for recreating the above lock system but in a more generic way.

prisma/schema.prisma
resource-lock/resource-lock.service.ts
resource-lock/resource-lock.module.ts
src/test.controller.ts

Like this, we can easily Lock any resource using this module now whenever and where ever we want. That's it for this post, Happy Codding 🎉😎🤘.

--

--

No responses yet