Build a file upload service with NodeJS, Typescript, Clean Architecture and AWS S3
Tags: node, typescript, aws
Published: 2021-01-29 16:19:19

In the old days, before that cloud thing become what it’s today, the way that the programs store their files (images, documents, etc) was a little different from now.

We had our local servers, running our applications locally and any type of file that was uploaded, was also stored in the same server (or not, but still locally) that the application was.

The problem with that architecture is that it can lead to several problems for our server, especially if the amount of the files that will be stored was meaningful (GB of files for example). The two main problems with that are the storage and the security. The storage could leave our server to become slow and the security, in case of loss of files, there’s no comment, especially if those files are confidential.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/yzjjsctmq47ep7rf61z5.jpeg)
*Client-Server architecture with local servers — https://www.sciencedirect.com/topics/computer-science/client-server-architecture*

Today the scenario is a little different, instead of local servers, we have a lot of cloud providers who provide us several different services, including storage services. In this example, I’ll show you how to create an API with NodeJS, Express and Typescript, to handle and upload files to AWS S3 (Simple Storage Service), also using Clean Architecture, IoC, SOLID principles and multer to handle the form-data that we’ll send.

I’m assuming that you already have an AWS account and an IAM user with the right permissions to use S3.

## API Structure
Let’s get started from our domain layer. In NodeJS environments, we don’t have the [File Interface](https://developer.mozilla.org/pt-BR/docs/Web/API/File) provided for us in the browser, so we need to create it on our own. So, inside the **domain** folder, let’s create the **models/file.ts**

{% gist https://gist.github.com/joaosczip/f5feef4bf78973ab7f84c0e90e1b58ca.js %}

This interface provides all the information that we need to handle and manipulate the incoming files. It’s very similar to the interface from the browsers.

And we also need an interface in our domain to represent the response from the file upload action. In our case, it’ll be very simple, just the path from the object in the storage service.

{% gist https://gist.github.com/joaosczip/2f57d492b181655412e11e3387de1faf.js %}

Now, we can start with our principal use case, the File Upload. Inside **domain**, let’s create the file **usecases/file-upload.ts**

{% gist https://gist.github.com/joaosczip/3cd539aad33a7a66c66e2f019e8bf33c.js %}

Remembering that our use case is just the contract. The implementation will be in the **application** layer. As you can see, the imports are made with the [tsconfig-paths](https://www.npmjs.com/package/tsconfig-paths), to be cleaner and flexible to changes.

When I have absolute knowledge of what I need to implement and what I’ll use to do that, I always start with the domain layer, because it’s the core of our service.

Getting started with our concrete implementation, in the application layer, let’s create a class that will implement the FIleUpload interface, this class will be responsible to group the received files from the controller and send them to the infra service that will communicate with the AWS SDK.

Before creating our class, let’s define the protocol for the infra service, we’ll call him **FileUploader** and place it in the **application/protocols/file-uploader.ts**

{% gist https://gist.github.com/joaosczip/6d00efd2b31208851545f17e31f5ed1e.js %}

Now, we’ll be able to create our implementation to FileUpload (the use case, not the infra protocol). Our concrete class will be called **RemoteFileUpload**.

{% gist https://gist.github.com/joaosczip/7af302f025cc2d1527af0118f0ade53f.js %}

This is a very simple implementation, as you can see, we’re implementing the FileUpload and using [tsyringe](https://www.npmjs.com/package/tsyringe) as IoC container to inject an implementation of FIleUploader (it’s not created yet).

We need to add the decorator **@injectable** to say that all the dependencies of the class will be injected when the application starts. The **@inject** decorator receives a token that we want to resolve, in our case, the FileUploader.

Now we need to create the class that will implement the FIleUploader and communicates with the [aws-sdk](https://www.npmjs.com/package/aws-sdk). This class will be in the infra layer, so, let’s create the **infra/aws-file-uploader.ts**.

{% gist https://gist.github.com/joaosczip/eb1fd170b36d6d149ddb0f9ae43cf1ea.js %}


This class uses the aws-sdk library (don’t forget to install it) to communicate with the AWS S3 and make the uploads. It can send just a single or a list of files (one per time). Here, the implementation isn’t the most important, pay attention to the architecture details, the way I choose to implement was just what meets my needs.

As you can see, I’m using some config file to store the bucket name and the region, this file uses the env variables that I defined in my docker-compose (you can define in your .env if running locally).

{% gist https://gist.github.com/joaosczip/cf92777492fefc7afc00f4add4f41f32.js %}


Remember that in the actual version of the sdk there is no more need to fill the aws secret and key when instantiating any service, it’ll look for those values in your environment.

With our application and infra layer completes, it’s time to create the controller that will handle the requests and will call the use case with the files.

{% gist https://gist.github.com/joaosczip/68fd4d9508ef0f3280d872db93c0d101.js %}

The controller also uses the IoC container to receive a FileUpload instance, which in your case will be the **RemoteFileUpload**. I won’t get deep into the details of the **HttpRequest** and **HttpResponse** types, those are just to abstract the Express response and request parameters. The interface that the controller was implementing, have just the method handle, that will receive the request and return a response.

With the controller created, let’s create our route and call our controller inside it. Another thing to notice about the route is that we need to use the [multer](https://www.npmjs.com/package/multer) to handle the files on the request (because we can’t send files on JSON).

Because multer has his own type of File, we created a middleware to map the multer file to our own File interface.

{% gist https://gist.github.com/joaosczip/408069d96b77c097ca87b4c250f9c4da.js %}


{% gist https://gist.github.com/joaosczip/1e13caccbac3d5c592b777147a083824.js %}

As you can see, we first added the **upload** middleware from multer and after that, our own **fileHandler** middleware, so, when passing the request to the controller, the files will be mapped to the format that we expect and inside the body.

Now, the rest is just configuration. We need to configure our service startup, to use express and also the IoC container with the map of **contract => implementation**.

{% gist https://gist.github.com/joaosczip/41b5a45545d10684ca818924e6f04503.js %}

{% gist https://gist.github.com/joaosczip/51347bbd1e1254dbf6ff2ed7531f99b9.js %}

Remember to put the import of the IoC inside your entrypoint.

{% gist https://gist.github.com/joaosczip/bcb177caa03a3b12234cf6dae0ae65ff.js %}

I hope that this tutorial will help you clarify something, like handling files with express, IoC container, usage of AWS SDK and files upload.

The goal of this article was to explain how we can create a very robust and flexible architecture even in cases that we need to communicate with external services and/or use third-party libraries. The focus wasn’t on the Clean Architecture itself, but what we can do using the principles behind her and some SOLID principles.

I’ll leave the link to the repository [here](https://github.com/joaosczip/photo-upload-ms) if you are interested to see how the project got.