Data Access
DAO (Data Access Object)
Also known as TDG (Table Data Gateway), it is a Table oriented pattern. (Oriented to Database a table)
This pattern is intended to interact with your Database tables and return table records.
Repository
Mediates the Domain Layer and the Data Layer (Persistense).
It purpose is to persist Domain Objects and return either Aggregates or Domain Objects.
Gateway
A way to obtain data from a external system.
ORM (Object Relational Mapper)
The ORM responsibility is to MAP the database to the domain.
In ORM, the model class mirrors the database table.
Usually only primitive types, since they come from the database.
Registry
A well known object (known by all), useful for locating other objects/services.
Registry
Pattern is very important for Dependency Injection
.
Serves basically as a Dependency pool.
Implementing using Singleton
export default class Registry {
private dependencies: {[name: string]: any} = {};
private static instance: Registry;
private constructor() {}
provide(name: string, dependency: any) {
this.dependencies[name] = dependency;
}
inject(name: string) {
return this.dependencies[name];
}
static getInstance() {
if (!Registry.instance) Registry.instance = new Registry();
return Registry.instance;
}
}
Use it anywhere on the code to, provide (create) and inject (get) other class instances (dependencies).
Example (without decorators
)
decorators
)This
const userDAO = new UserDAO();
new Signup(userDAO);
class Signup {
constructor (private readonly userDAO: UserDAO) {}
execute(value: string) {
this.userDAO.getUserByID(value);
}
}
Will be substituted by
In the main.ts
we instanciate and provide to the Registry
all the classes we want.
// This will automatically create Registry instance, and set the userDAO instance
Registry.getInstance().provide('userDAO', new UserDAO());
At the Signup.ts
for example we will grab the UserDAO
instance created in the main.ts
. And as you can see, no classes had to be passed to the constructor as parameter.
class Signup {
userDAO?: UserDAO;
constructor () {
this.userDAO = Registry.getInstance().inject('userDAO');
}
execute(value: string) {
this.userDAO?.getUserByID(value);
}
}
Example (with decorators
) (in typescript
)
decorators
) (in typescript
)The same example above, will be substituted by:
export default class Registry {
// The same as above
}
// decorator for Registry
export function inject(name: string) {
return function(target: any, propertyKey: string) {
target[propertyKey] = new Proxy({}, {
get(target: any, propertyKey: string) {
const dependency = Registry.getInstance().inject(name);
return dependency[propertyKey];
}
});
}
}
// This will automatically create Registry instance, and set the userDAO instance
Registry.getInstance().provide('userDAO', new UserDAO());
import { inject, Registry } from 'Regestry';
class Signup {
@inject('userDao')
userDAO?: UserDAO;
execute(value: string) {
this.userDAO?.getUserByID(value);
}
}
Last updated