Skip to content

Commit

Permalink
Add relationship handling for resource creation
Browse files Browse the repository at this point in the history
  • Loading branch information
Koray Koska committed May 10, 2017
1 parent 6f4fdfa commit f288d14
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
27 changes: 25 additions & 2 deletions Sources/VaporJsonApi/Resources/JsonApiResourceController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -171,10 +171,33 @@ public extension JsonApiResourceController {
let node = bodyData?["attributes"]?.makeNode()
var resource = try Resource(node: node)

// TODO: Set relationships
// TODO: Check jsonapi document for correct to-many relationship handling
if let relationships = bodyData?["relationships"]?.object {
for r in relationships {

// Get relationships
let parents = try resource.parentRelationships()
let children = try resource.childrenRelationships()
let siblings = try resource.siblingsRelationships()

if let parent = parents[r.key] {
guard let id = r.value.object?["id"]?.string, let type = r.value.object?["type"]?.string else {
throw JsonApiBadRequestError(title: "Bad Request", detail: "The relationship \(r.key) must have a type and id value.")
}
guard let p = try parent.type.find(id) else {
throw JsonApiRecordNotFoundError(id: id)
}
guard let setter = parent.setter else {
throw JsonApiRelationshipNotAllowedError(relationship: type)
}

try setter(p)
} else if let _ = children[r.key] {
throw JsonApiBadRequestError(title: "Setting to-many relationships not allowed", detail: "You set to-many relationships in the same step as creating a resource right now. You tried to set \(r.key) for this resource.")
} else if let _ = siblings[r.key] {
throw JsonApiBadRequestError(title: "Setting to-many relationships not allowed", detail: "You set to-many relationships in the same step as creating a resource right now. You tried to set \(r.key) for this resource.")
} else {
throw JsonApiRelationshipNotAllowedError(relationship: r.key)
}
}
}
try resource.save()
Expand Down
11 changes: 11 additions & 0 deletions Sources/VaporJsonApi/Response/JsonApiError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,17 @@ public class JsonApiParameterNotAllowedError: JsonApiGeneralError {
}
}

public class JsonApiRelationshipNotAllowedError: JsonApiGeneralError {

public init(title: String, detail: String) {
super.init(status: Status.badRequest, code: String(Status.badRequest.statusCode), title: title, detail: detail)
}

public convenience init(relationship: String) {
self.init(title: "Relationship not allowed", detail: "\(relationship) is not allowed.")
}
}

public class JsonApiParameterMissingError: JsonApiGeneralError {

public init(title: String, detail: String) {
Expand Down

0 comments on commit f288d14

Please sign in to comment.