Apollo GraphQL 突变结果未使用 PostgreSQL 更新,但适用于 SQLite

Apollo GraphQL mutation results not updating with PostgreSQL but works with SQLite

为什么我使用 SQLite 从我的更新解析器获取更新数据而不是 postgress?如果重要的话,我也在为 ORM 使用 Sequelize。

关于 Apollo 和数据库的一般性问题。基本上我有一个更新用户解析器,它更新用户的一些字段并 returns 返回用户。使用 SQLite 时,返回的数据是正确的更新用户。但是,当我切换到 postgres 时,数据总是落后 1 个更新?因此,当我最初使用 postgres 更新用户时,没有任何变化,但下次更新时,我会从上一次更新中获取数据,依此类推。我只是很困惑,因为我没有更改任何代码,只是更改了它使用的数据库。 Apollo 与不同数据库的行为是否不同,或者 postgress 与 sqlite 的行为是否不同?

// model

"use strict";
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define(
    "User",
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      firstName: DataTypes.STRING,
      lastName: DataTypes.STRING,
      userType: DataTypes.STRING,
    },
  );

  User.associate = function(models) {
  };
// typeDef

  type User {
    id: ID!
    firstName: String
    lastName: String
    userType: String
    createdAt: String
    updatedAt: String
  }
// resolver

    async updateUser(
      root,
      {
        id,
        firstName,
        lastName,
        userType,
      },
      { models }
    ) {
      models.User.update(
        {
          firstName: firstName,
          lastName: lastName,
          userType: userType,
        },
        {
          where: { id: id }
        }
      );
      return models.User.findByPk(id);
    },
//query

mutation {
  updateEmployee(
    id: 1
    firstName: "testName"
    lastName: "testUpdate"
    employeeID: "12345"
  ){
    id
    firstName
    lastName
    employeeID
    createdAt
    updatedAt
  }
}

您没有在等待 update 调用,因此 findByPk returns 在 update 调用之前的用户有机会完成。

await models.User.update(  // <-- here
  {
    firstName: firstName,
    lastName: lastName,
    userType: userType,
  },
  {
    where: { id: id }
  }
);
return models.User.findByPk(id);

FWIW,如果您使用的是 Postgres,则可以通过提供 returning 选项来使用单个调用:

const [_, user] = await models.User.update(
  {
    firstName: firstName,
    lastName: lastName,
    userType: userType,
  },
  {
    where: { id: id },
    returning: true,
  }
);
return user;