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

Custom Sequelize Datataype #366

Open
devin-efw opened this issue Aug 11, 2023 · 1 comment
Open

Custom Sequelize Datataype #366

devin-efw opened this issue Aug 11, 2023 · 1 comment

Comments

@devin-efw
Copy link

devin-efw commented Aug 11, 2023

How can we define a custom sequelize datatype?

Sequelize is automatically converting the date to include time zone adjustments. Because of this, inserts into the mssql DB are failing.

I would like to define a datatype to override the stringify method for the Date datatype. Doing so, following the sequelize documentation, I'm unable to override the method (https://sequelize.org/docs/v6/other-topics/extending-data-types/) is not working properly.

@devin-efw
Copy link
Author

devin-efw commented Aug 21, 2023

Working example:

import { DataTypes, Sequelize, Utils } from "sequelize";

const DATE = DataTypes.DATE.prototype.constructor;

export class MSSQLDATE extends DATE {
    constructor(length: any) {
        super(length);
    }

    // Method to convert to SQL representation
    toSql() {
        return "DATE";
    }

    // Method to stringify date for DB
    stringify(date: Date, options: object) {
        return this._applyTimezone(date, options).format('YYYY-MM-DD HH:mm:ss.SSS');
    }
}

export function initCustomDatatypes() {
    // Apply classToInvokable transformation
    const invokableMSSQLDATE = Utils.classToInvokable(MSSQLDATE);

    // Add key property
    MSSQLDATE.prototype.key = 'MSSQLDATE';

    //@ts-ignore
    // Expose the class through Sequelize and DataTypes
    Sequelize.MSSQLDATE = DataTypes.MSSQLDATE = invokableMSSQLDATE;
};

Make sure this code is executed before sequelize is initialized. I imported and called the initCustomDatatatypes function in a utilities database mixin. I imported and used the MSSQLDATE class as a datatype type in the sequelize model file.

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