sql >> Base de Datos >  >> RDS >> PostgreSQL

¿Cómo ignorar SequelizeUniqueConstraintError en Sequelize?

Mi solución.

Agregar método updateOrCreate

Product.updateOrCreate = function (options) {
    return this.findOrCreate(options).then(res => {
        let [row, created] = res;
        if (created) return [row, created];
        return row.update(options.defaults, options.transaction)
            .then(updated => [updated, created]);
    })
};
Tag.updateOrCreate = function (options) {
    return this.findOrCreate(options).then(res => {
        let [row, created] = res;
        if (created) return [row, created];
        return row.update(options.defaults, options.transaction)
            .then(updated => [updated, created]);
    })
};

usar

let data = {
    title: 'Chair',
    tag: [
        {name: 'Alpha'},
        {name: 'Beta'}
    ]
};
return sequelize.transaction().then(t => {
    return Product.updateOrCreate({
        where: {title: data.title},
        defaults: data,
        transaction: t
    }).then(res => {
        let [product] = res;
        return Promise.all(data.tag.map(tag => {
            return Tag.updateOrCreate({
                where: {name: tag.name},
                defaults: tag,
                transaction: t
            }).then(res => {
                let [tag] = res;
                return Promise.resolve(tag);
            }).catch(err => Promise.reject(err.message));
        })).then(() => {
            t.commit();
            sequelize.close();
        }).catch(err => Promise.reject(err));
    }).catch(err => {
        t.rollback();
        sequelize.close();
    });
});