9

今天检查了一些放大文档(我知道这个说它是iOS场景中的预览),但我遇到了障碍。

假设

  1. 在我的 iOS 项目中正确配置了 Amplify。我可以将数据推送到Person并查询Amplify.API
  2. 架构已定义为:
type Person @model {
  id: ID!
  name: String!
  possessions: [Thing] # list of things this person owns.
    @connection(keyName: "byPerson", fields: ["id"])
}

type Thing @model
           @key(name: "byPerson", fields: ["personId"]) {

  id: ID!
  name: String!
  personId: ID!
  ownerOfThings: Person # defining the 'belongsTo' property.
    @connection(fields: ["personId"])
}

这会生成以下代码:

public struct Person: Model {
  public let id: String
  public var name: String
  public var possessions: List<Thing>?

  public init(id: String = UUID().uuidString,
      name: String,
      possessions: List<Thing>? = []) {
      self.id = id
      self.name = name
      self.possessions = possessions
  }
}

public struct Person: Model {
  public let id: String
  public var name: String
  public var ownerOfThings: Person?

  public init(id: String = UUID().uuidString,
      name: String,
      ownerOfThings: Person? = nil) {
      self.id = id
      self.name = name
      self.ownerOfThings = ownerOfThings
  }
}

这是我遇到麻烦的地方。Amplify.API似乎没有将我的对象及其相关数据保存在单个突变中。我必须将其称为嵌套操作才能产生效果。

// sample on how I am trying to save data.

var thing = Thing(name: "Long Claw")
let person = Person(
  name: "Jon Snow",
  possessions: List([ thing ])
)

Amplify.API.mutate(of: person, type: .create) { ev in
  // doing something with the event.
  print(String(describing: ev)) // this works. It saves the instance to DynamoDB
  // unfortunately, it did not save the instance of thing... let's try to correct this.

  thing.ownerOfThings = person
  Amplify.API.mutate(of: thing, type: .create) { ev2 in
    // do something else with this...
    print(String(describing: ev2))
    // this ^ crashes badly...
  }
}

上面的代码将生成类似于以下内容的输出:

Result.success(Person(id: "EC4BEEE1-C1A1-4831-AB86-EA1E22D8AD48", name: "Jon Snow", possessions: nil))

GraphQLResponseError<Thing>: GraphQL service returned a successful response containing errors: [Amplify.GraphQLError(message: "Variable \'input\' has coerced Null value for NonNull type \'ID!\'", locations: Optional([Amplify.GraphQLError.Location(line: 1, column: 26)]), path: nil, extensions: nil)]

我尝试将关系声明为:

type Person @model {
  id: ID!
  name: String!
  possessions: [Thing] # list of things this person owns.
    @connection(keyName: "byPerson", fields: ["id"])
}

type Thing @model
           @key(name: "byPerson", fields: ["personId"]) {

  id: ID!
  name: String!
  personId: ID!
  # ownerOfThings: Person
  #   @connection(fields: ["personId"]) # Not belongsTo for you!
}

或者这个的变体,定义possessionsas possessions: [Thing] @connection

所有这些都会产生各种(尽管有些是相关的)错误,使我无法存储我的数据。

那么,问题来了: 在iOS中如何指定关系来保存呢?

4

0 回答 0