fullstack-apollo-express-postgresql-boilerplate icon indicating copy to clipboard operation
fullstack-apollo-express-postgresql-boilerplate copied to clipboard

About TypeError: sequelize.import is not a function

Open mejustdev opened this issue 5 years ago • 2 comments

I am in the Connecting Resolvers and Database part. I got this warning: TypeError: sequelize.import is not a function. I searched about it. I could not find any answer that fits my problem.

This is my Sequelize version: "sequelize": "^6.3.4",

Maybe it is related with the deprecation of import function in Sequelize? How can we refactor our code?

I think this kind of problems can happen everytime. How can we deal with those?

mejustdev avatar Aug 21 '20 09:08 mejustdev

the import function doesn't work. you could change the code to following:

import "dotenv/config";
import Sequelize from "sequelize";
import path from "path";
import fs from "fs";

const basename = path.basename(__filename);

const db = {};

const sequelize = new Sequelize(
  process.env.DATABASE,
  process.env.DATABASE_USER,
  process.env.DATABASE_PASSWORD,
  {
    dialect: "postgres",
  },
);

fs.readdirSync(path.join(__dirname, "/models"))
  .filter(
    (file) =>
      file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js",
  )
  .forEach((file) => {
    const model = require(path.join(__dirname, "/models", file)).default(
      sequelize,
      Sequelize.DataTypes,
    );
    db[model.name] = model;
  });

Object.keys(db).forEach((key) => {
  if (db[key].associate) {
    db[key].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

export default db;

On the src/index.js file replace the context with the following piece of code:

import db from './models';

context: async ({ req, connection }) => {
    if (connection) {
      return { db };
    }
    if (req) {
      const me = await getMe(req);
      return {
        db,
        me,
        secret: process.env.SECRET,
      };
    }
  },

tusharkhatiwada avatar Aug 23 '20 13:08 tusharkhatiwada

Thanks for the solution. worked with some addition 👍

mejustdev avatar Aug 25 '20 22:08 mejustdev