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

About TypeError: sequelize.import is not a function #122

Open
mejustdev opened this issue Aug 21, 2020 · 2 comments
Open

About TypeError: sequelize.import is not a function #122

mejustdev opened this issue Aug 21, 2020 · 2 comments

Comments

@mejustdev
Copy link

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?

@tusharkhatiwada
Copy link

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,
      };
    }
  },

@mejustdev
Copy link
Author

Thanks for the solution. worked with some addition 👍

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

2 participants