Skip to content

Instantly share code, notes, and snippets.

@getanwar
Last active September 2, 2018 15:13
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 getanwar/cf019c62f875a824a23dd27a50942625 to your computer and use it in GitHub Desktop.
Save getanwar/cf019c62f875a824a23dd27a50942625 to your computer and use it in GitHub Desktop.
Experiment: Mongoose like static & virtual methods
<script>
const users = [{
first: "Anwar",
last: "Hussain",
age: 27,
profession: 'dev'
}, {
first: "Rafsan",
last: "Hasemi",
age: 25,
profession: 'dev'
}];
// Creating constructor funciton
function User(obj) {
for (let key in obj) {
this[key] = obj[key];
}
}
// Creating static method to select first result
User.findOne = function (obj) {
// Think this as database query
const result = users.filter(user => {
let matched = false;
for (let f_key in obj) {
matched = user[f_key] === obj[f_key]
if (!matched) return matched;
}
return matched;
});
if (!result.length) {
return {
error: 'No data found'
}
}
return new User(result[0]);
};
// Creating static method to select all
User.find = function (obj) {
// Think this as database query
const results = users.filter(user => {
// return all data if no params passed
if (obj == undefined || !Object.keys(obj).length) return true;
let matched = false;
for (let f_key in obj) {
matched = user[f_key] === obj[f_key]
if (!matched) return matched;
}
return matched;
});
if (!results.length) {
return {
error: 'No data found'
}
}
return results.map((result) => {
return new User(result);
});
};
// Defining virtual property
User.virtual = function (path) {
return {
get(callback) {
Object.defineProperty(User.prototype, path, {
get: callback,
enumerable: true,
configurable: true
});
return this;
},
set(callback) {
Object.defineProperty(User.prototype, path, {
set: callback,
enumerable: true,
configurable: true
});
return this;
}
}
};
// Setting how getter and setter should behave
User
.virtual('fullName')
.get(function () {
return `${this.first} ${this.last}`;
})
.set(function (name) {
const [first, last] = name.split(' ');
this.first = first;
this.last = last;
});
// instance object
const anwar = User.findOne({first: "Anwar"});
const allUsers = User.find();
console.log(anwar, allUsers);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment