Created
February 28, 2023 13:38
-
-
Save skysan87/eb461cdccee54c379e79933933ed8859 to your computer and use it in GitHub Desktop.
[JavaScript] DAO pattern with Reflect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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