Skip to content

Instantly share code, notes, and snippets.

@skysan87
Created February 28, 2023 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skysan87/eb461cdccee54c379e79933933ed8859 to your computer and use it in GitHub Desktop.
Save skysan87/eb461cdccee54c379e79933933ed8859 to your computer and use it in GitHub Desktop.
[JavaScript] DAO pattern with Reflect
// DataModel
class UserModel {
constructor(data = {}) {
this.id = data.id ?? null;
this.name = data.name ?? '';
}
}
class BookModel {
constructor(data = {}) {
this.id = data.id ?? null;
this.title = data.title ?? '';
}
}
// Storage
const memory = new Map();
// DAO
function DataAccess (key, model) {
return class {
static save (value) {
const data = Reflect.construct(model, [value]);
memory.set(key, data);
}
static load () {
const data = memory.get(key);
return Reflect.construct(model, [data]);
}
}
}
class User extends DataAccess('user', UserModel) {
constructor() {
super();
}
}
class Book extends DataAccess('book', BookModel) {
constructor() {
super();
}
/**
* @param {BookModel} data
*/
static save (data) {
// do something...
super.save(data);
}
}
User.save({ id: 1, name: 'hoge' });
console.log(User.load());
const newBook = new BookModel();
newBook.id = 123;
newBook.title = 'new book';
Book.save(newBook);
console.log(Book.load());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment