【问题标题】:Apollo GraphQL mutation results not updating with PostgreSQL but works with SQLiteApollo GraphQL 突变结果不使用 PostgreSQL 更新,但适用于 SQLite
【发布时间】:2019-09-23 03:49:37
【问题描述】:

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

关于 Apollo 和数据库的一般问题。基本上我有一个更新用户解析器,它更新用户的一些字段并返回用户。使用 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
  }
}

【问题讨论】:

    标签: javascript postgresql apollo apollo-client apollo-server


    【解决方案1】:

    您没有等待update 调用,因此findByPkupdate 调用有机会完成之前返回用户。

    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;
    

    【讨论】:

      猜你喜欢
      • 2019-08-01
      • 2019-03-08
      • 2019-04-07
      • 2021-02-17
      • 2019-06-11
      • 2018-11-10
      • 2020-10-20
      • 2017-10-18
      • 2016-11-25
      相关资源
      最近更新 更多