Using an object as column wrapper in a Sequelize model

I am in the process of building a REST api on top of an existing database schema using Node, Express, Sequelize and Mssql.

I am not able/allowed to modify the existing database as there is a legacy application relying on its structure with many hardcoded SQL-queries.

I've read through Sequelize's documentation without finding anything about how to define a model to achieve this. Is this possible and if so how can this be done?

What i want to return from the api

{
    id: 1234,
    title: "abc"
    images: ["img.jpg", "img.jpg", "img.jpg"]
}

What the table looks like:

 +----+-------+----------+----------+----------+
 | id | title |  image_1 |  image_2 |  image_3 |
 +----+-------+----------+----------+----------+
 | 1  | abc   | img1.jpg | img2.jpg | img3.jpg |
 +----+-------+----------+----------+----------+

My incomplete model-definition

const News = sequelize.define(
    "news",
    {
        id: Sequelize.INTEGER,
        title: Sequelize.TEXT,
        images: ????
    }
)

Upvotes: 0

Views: 774

Answers (1)

Kormelad
Kormelad

Reputation: 36

You can try to make the "images" field with getter:

images: {
    type: Sequelize.ARRAY(Sequelize.STRING),
    get() {
        const imageFields = ['image_1', 'image_2', 'image_3'];
        return imageFields.map(this.getDataValue);
    },
}

UPD: The method above works for defining inside an existing property.

If you want to make it inside a model try the following:

const News = sequelize.define(
    "news",
    { ... },
    {
        getterMethods: {
            name() {
                const imageFields = ['image_1', 'image_2', 'image_3'];
                return imageFields.map(field => this[field]);
            }
        }
    }
)

Upvotes: 2

Related Questions