Last active
July 3, 2019 18:37
-
-
Save AlekzZz/8f192474ae65b62bfda5ecd96e3db3c8 to your computer and use it in GitHub Desktop.
Goal model example
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
import { Sql as SqlAdapter } from '@adapters'; | |
import { Uuid, toJson, attr } from '@app/lib/utils'; | |
import { ATTR_TYPE_STRING, ATTR_TYPE_NUMBER } from '@constants'; | |
const table = 'goals'; | |
const adapter = SqlAdapter({ table }); | |
const currentYear = new Date().getFullYear(); | |
/** | |
* Goal Model | |
*/ | |
const Goal = ({ id, user_id, type, value, year } = {}) => { | |
let instance = { | |
id: attr(ATTR_TYPE_STRING, id, null), | |
user_id: attr(ATTR_TYPE_STRING, user_id), | |
type: attr(ATTR_TYPE_STRING, type), | |
value: attr(ATTR_TYPE_NUMBER, value), | |
year: attr(ATTR_TYPE_NUMBER, year, currentYear) | |
}; | |
Object.defineProperty(instance, 'isNew', { | |
enumerable: false, | |
value: !Boolean(instance.id) | |
}); | |
Object.defineProperty(instance, 'toJson', { | |
enumerable: false, | |
value: () => toJson(instance) | |
}); | |
/** | |
* Smart save: create/update in one | |
*/ | |
Object.defineProperty(instance, 'save', { | |
enumerable: false, | |
value: () => { | |
if (instance.isNew) { | |
instance.id = Uuid(); | |
return adapter.create(instance).then(() => instance); | |
} else { | |
return adapter.update(instance, { where: { id: instance.id } }).then((response) => Goal(response)); | |
} | |
} | |
}); | |
/** | |
* Deletes current record from db | |
*/ | |
Object.defineProperty(instance, 'delete', { | |
enumerable: false, | |
value: () => { | |
let { id } = instance; | |
if (!id) { | |
throw new Error('Cannot delete non-existing record.'); | |
} | |
return adapter.delete({ where: { id } }); | |
} | |
}); | |
return Object.seal(instance); | |
}; | |
/** | |
* Static findOne | |
* @param {Object} options | |
* @return {Goal} | |
*/ | |
Goal.findOne = (options) => adapter.findOne(options).then((record) => Goal(record)); | |
/** | |
* Static findAll | |
* @param {Object} options | |
* @return {Array<Goal>} | |
*/ | |
Goal.findAll = (options) => { | |
return adapter.findAll(options).then((records) => { | |
return records.map((record) => Goal(record)); | |
}); | |
}; | |
export default Goal; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment