Home > Mobile >  Where do you put third party libs when following Clean and Hexagonal Architecture? [closed]
Where do you put third party libs when following Clean and Hexagonal Architecture? [closed]

Time:10-07

I've been studying Clean Architecture, Hexagonal Architecture, and implementing pieces I find applicable to my application. I know both architectures talk about separating your domain from the outside world. All of the resources I've read use controllers, CLIs, repositories, and communication platforms like Twilio as examples of adapters. I'm using a lib for generating JWTs (JSON Web Token). My question is if the implementation for the lib belongs in the domain layer or outside of it. I only ask because all of the resources I've read never mention libs like validation, JWTs, and generating UUIDs in the outside layer. It's usually the stuff I've listed above like controllers and databases outside of the domain.

CodePudding user response:

As you mentioned Hexagonal Architecture cares about outside communication and tools like validation, JWTs, and generating UUIDs are regarded as part of the core application (Where the core is the internal logic of the app).

Regarding Clean Architecture when using 3rd party libs you should expose them using your own interface instead of directly using theirs.

Bad

//myService.js
class MyService {
    
    constructor(uuid){
        this.uuid = uuid;
    }

    save(...) {
        const id = this.uuid.v4(); // <--- hard to refactore if "uuid" will change its API
        ...
    }

}

//app.js
const uuid = require('uuid');

const MyService = require('./myService');
...
const FooService = require('./FooService');


const myService = new MyService(uuid);
...
const fooService = new FooService(uuid);



Good

//uuidFactoryProvider.js
function uuidFactoryProvider(uuid){
    return function uuidFactory() {
        return this.uuid.v4(); // <-- easy to refactore
    }
}

//myService.js
class MyService {
    
    constructor(uuidFactory){
        this.uuidFactory = uuidFactory;
    }

    save(...) {
        const id = uuidFactory();
        ...
    }

}

//app.js
const uuid = require('uuid');

const uuidFactoryProvider = require('./uuidFactoryProvider');
const MyService = require('./myService');
...
const FooService = require('./FooService');


const uuidFactory = uuidFactoryProvider(uuid);
const myService = new MyService(uuidFactory);
...
const fooService = new FooService(uuidFactory);

By wrapping the 3rd party libs with your own API the codebase will have time minimal dependency on the libs API.

  • Related