|
| 1 | +/* |
| 2 | + This source file is part of the Swift.org open source project |
| 3 | + |
| 4 | + Copyright (c) 2021 Apple Inc. and the Swift project authors |
| 5 | + Licensed under Apache License v2.0 with Runtime Library Exception |
| 6 | + |
| 7 | + See https://swift.org/LICENSE.txt for license information |
| 8 | + See https://swift.org/CONTRIBUTORS.txt for Swift project authors |
| 9 | +*/ |
| 10 | + |
| 11 | +import Foundation |
| 12 | + |
| 13 | +/// A utility type for applying JSON patches. |
| 14 | +/// |
| 15 | +/// Use this type to apply ``JSONPatchOperation`` values onto JSON. |
| 16 | +public struct JSONPatchApplier { |
| 17 | + /// Creates a new JSON patch applier. |
| 18 | + public init() {} |
| 19 | + |
| 20 | + /// Applies the given patch onto the given JSON data. |
| 21 | + /// |
| 22 | + /// - Parameters: |
| 23 | + /// - patch: The patch to apply. |
| 24 | + /// - jsonData: The data on which to apply the patch. |
| 25 | + /// - Returns: The JSON data with the patch applied. |
| 26 | + /// - Throws: This function throws an ``Error`` if the application was not successful. |
| 27 | + public func apply(_ patch: JSONPatch, to jsonData: Data) throws -> Data { |
| 28 | + let json = try JSONDecoder().decode(JSON.self, from: jsonData) |
| 29 | + |
| 30 | + // Apply each patch operation one-by-one to the JSON, and throw an error if one of the patches could not |
| 31 | + // be applied. |
| 32 | + let appliedJSON = try patch.reduce(json) { json, operation in |
| 33 | + guard let newValue = try apply(operation, to: json, originalPointer: operation.pointer) else { |
| 34 | + // If the application of the operation onto the top-level JSON element results in a `nil` value (i.e., |
| 35 | + // the entire value was removed), throw an error since this is not supported. |
| 36 | + throw Error.invalidPatch |
| 37 | + } |
| 38 | + return newValue |
| 39 | + } |
| 40 | + |
| 41 | + return try JSONEncoder().encode(appliedJSON) |
| 42 | + } |
| 43 | + |
| 44 | + private func apply(_ operation: JSONPatchOperation, to json: JSON, originalPointer: JSONPointer) throws -> JSON? { |
| 45 | + // If the pointer has no path components left, this is the value we need to update. |
| 46 | + guard let component = operation.pointer.pathComponents.first else { |
| 47 | + switch operation { |
| 48 | + case .replace(_, let value): |
| 49 | + if let json = value.value as? JSON { |
| 50 | + return json |
| 51 | + } else { |
| 52 | + // If the value is not encoded as a `JSON` value already, convert it. |
| 53 | + let data = try JSONEncoder().encode(value) |
| 54 | + return try JSONDecoder().decode(JSON.self, from: data) |
| 55 | + } |
| 56 | + case .remove(_): |
| 57 | + return nil |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + let nextOperation = operation.removingPointerFirstPathComponent() |
| 62 | + |
| 63 | + // Traverse the JSON element and apply the operation recursively. |
| 64 | + switch json { |
| 65 | + case .dictionary(var dictionary): |
| 66 | + // If the element is a dictionary, modify the value at the key indicated by the current path component |
| 67 | + // of the pointer. |
| 68 | + guard let value = dictionary[component] else { |
| 69 | + throw Error.invalidObjectPointer( |
| 70 | + originalPointer, |
| 71 | + component: component, |
| 72 | + availableObjectKeys: dictionary.keys |
| 73 | + ) |
| 74 | + } |
| 75 | + |
| 76 | + dictionary[component] = try apply(nextOperation, to: value, originalPointer: originalPointer) |
| 77 | + |
| 78 | + return .dictionary(dictionary) |
| 79 | + case .array(var array): |
| 80 | + // If the element is an array, modify the value at the index indicated by the current integer path |
| 81 | + // component of the pointer. |
| 82 | + guard let index = Int(component), array.indices.contains(index) else { |
| 83 | + throw Error.invalidArrayPointer( |
| 84 | + originalPointer, |
| 85 | + index: component, |
| 86 | + arrayCount: array.count |
| 87 | + ) |
| 88 | + } |
| 89 | + |
| 90 | + if let newValue = try apply(nextOperation, to: array[index], originalPointer: originalPointer) { |
| 91 | + array[index] = newValue |
| 92 | + } else { |
| 93 | + array.remove(at: index) |
| 94 | + } |
| 95 | + |
| 96 | + return .array(array) |
| 97 | + default: |
| 98 | + // The pointer is invalid because it has a non-empty path component, but the JSON element is not |
| 99 | + // traversable, i.e., it's a number, string, boolean, or null value. |
| 100 | + throw Error.invalidValuePointer( |
| 101 | + originalPointer, |
| 102 | + component: component, |
| 103 | + jsonValue: String(describing: json) |
| 104 | + ) |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + /// An error that occured during the application of a JSON patch. |
| 109 | + public enum Error: DescribedError { |
| 110 | + /// An error indicating that the pointer of a patch operation is invalid for a JSON object. |
| 111 | + /// |
| 112 | + /// - Parameters: |
| 113 | + /// - component: The component that's causing the pointer to be invalid in the JSON object. |
| 114 | + /// - availableKeys: The keys available in the JSON object. |
| 115 | + case invalidObjectPointer(JSONPointer, component: String, availableKeys: [String]) |
| 116 | + |
| 117 | + |
| 118 | + /// An error indicating that the pointer of a patch operation is invalid for a JSON object. |
| 119 | + /// |
| 120 | + /// - Parameters: |
| 121 | + /// - component: The component that's causing the pointer to be invalid in the JSON object. |
| 122 | + /// - availableObjectKeys: The keys available in the JSON object. |
| 123 | + public static func invalidObjectPointer<Keys: Collection>( |
| 124 | + _ pointer: JSONPointer, |
| 125 | + component: String, |
| 126 | + availableObjectKeys: Keys |
| 127 | + ) -> Self where Keys.Element == String { |
| 128 | + return .invalidObjectPointer(pointer, component: component, availableKeys: Array(availableObjectKeys)) |
| 129 | + } |
| 130 | + |
| 131 | + /// An error indicating that the pointer of a patch operation is invalid for a JSON array. |
| 132 | + /// |
| 133 | + /// - Parameters: |
| 134 | + /// - index: The index component that's causing the pointer to be invalid in the JSON array. |
| 135 | + /// - arrayCount: The size of the JSON array. |
| 136 | + case invalidArrayPointer(JSONPointer, index: String, arrayCount: Int) |
| 137 | + |
| 138 | + /// An error indicating that the pointer of a patch operation is invalid for a JSON value. |
| 139 | + /// |
| 140 | + /// - Parameters: |
| 141 | + /// - component: The component that's causing the pointer to be invalid, since the JSON element is a non-traversable value. |
| 142 | + /// - jsonValue: The string-encoded description of the JSON value. |
| 143 | + case invalidValuePointer(JSONPointer, component: String, jsonValue: String) |
| 144 | + |
| 145 | + /// An error indicating that a patch operation is invalid. |
| 146 | + case invalidPatch |
| 147 | + |
| 148 | + public var errorDescription: String { |
| 149 | + switch self { |
| 150 | + case .invalidObjectPointer(let pointer, let component, let availableKeys): |
| 151 | + return """ |
| 152 | + Invalid dictionary pointer '\(pointer)'. The component '\(component)' is not valid for the object with \ |
| 153 | + keys \(availableKeys.sorted().map(\.singleQuoted).list(finalConjunction: .and)). |
| 154 | + """ |
| 155 | + case .invalidArrayPointer(let pointer, let index, let arrayCount): |
| 156 | + return """ |
| 157 | + Invalid array pointer '\(pointer)'. The index '\(index)' is not valid for array of \(arrayCount) \ |
| 158 | + elements. |
| 159 | + """ |
| 160 | + case .invalidValuePointer(let pointer, let component, let jsonValue): |
| 161 | + return """ |
| 162 | + Invalid value pointer '\(pointer)'. The component '\(component)' is not valid for the non-traversable \ |
| 163 | + value '\(jsonValue)'. |
| 164 | + """ |
| 165 | + case .invalidPatch: |
| 166 | + return "Invalid patch" |
| 167 | + } |
| 168 | + } |
| 169 | + } |
| 170 | +} |
0 commit comments