index.js 910 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const _ = require('lodash')
  2. const config = require('../../config')
  3. const bcrypt = require('bcrypt')
  4. const sequelize = require('./sequelize')
  5. const User = require('./user')
  6. const Session = require('./session')
  7. const Role = require('./role')
  8. const UserRole = User.belongsToMany(Role, { through: 'userRoles' })
  9. const upsert = async (Type, object, fields) => {
  10. if (!fields) {
  11. fields = ['key']
  12. }
  13. for (var field of fields) {
  14. if (!object[field]) {
  15. throw new Error(`Missing upsert field '${field}' in ${JSON.stringify(object)}.`)
  16. }
  17. }
  18. const existing = await Type.findOne({where: _.pick(object, fields)})
  19. if (existing) {
  20. Object.assign(existing, object)
  21. await existing.save()
  22. return existing
  23. } else {
  24. return await Type.create(object)
  25. }
  26. }
  27. module.exports = {
  28. init: () => {
  29. return sequelize.sync()
  30. },
  31. sequelize,
  32. User,
  33. Session,
  34. Role,
  35. UserRole,
  36. upsert
  37. }