Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using Sequelize as store #25

Open
ryanburnette opened this issue Jun 26, 2021 · 2 comments
Open

Using Sequelize as store #25

ryanburnette opened this issue Jun 26, 2021 · 2 comments

Comments

@ryanburnette
Copy link
Collaborator

ryanburnette commented Jun 26, 2021

I'm documenting a way to use Sequelize for store.

// models/objstore.js
'use strict';

module.exports = (sequelize, DataTypes) => {
  class ObjStore extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  }
  ObjStore.init(
    {
      id: {
        type: DataTypes.STRING,
        primaryKey: true,
        unique: true
      },
      attrs: {
        type: DataTypes.TEXT,
        get: function () {
          var str = this.getDataValue('attrs') || '{}';
          return JSON.parse(str);
        },
        set: function (val) {
          this.setDataValue('attrs', JSON.stringify(val));
        }
      }
    },
    {
      sequelize,
      modelName: 'ObjStore',
      timestamps: false
    }
  );
  return ObjStore;
};
// lib/store.js
'use strict';

var db = require('./models');

module.exports = {
  set: async function (id, attrs) {
    var [record, _] = await db.ObjStore.findOrCreate({ where: { id } });
    record.attrs = attrs;
    return record.save();
  },
  get: async function (id) {
    return db.ObjStore.findOne({ where: { id } }).then(function (record) {
      if (!record) {
        return false;
      }
      return record.get({ plain: true }).attrs;
    });
  }
};
@ryanburnette
Copy link
Collaborator Author

@coolaj86 Can you take a look at this? The flaw I see is that this may not update the attrs if a single attribute changes. Maybe I should make use of Object.assign. Even if that situation doesn't come up, it might be good to future proof it. Let me know if you have any feedback.

@ryanburnette ryanburnette changed the title sequelize store example Using Sequelize as store Jun 26, 2021
@ryanburnette
Copy link
Collaborator Author

@coolaj86 Another thing... this strategy has the date coming back as an ISO string. It seems to work, but is that reliable?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant