This repository has been archived by the owner on Dec 25, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUDImage.swift
131 lines (92 loc) · 2.19 KB
/
UDImage.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
//
// UDImage.swift
// UDClient
//
// Created by Omar Albeik on 7/15/17.
// Copyright © 2017 Udacity. All rights reserved.
//
import Foundation
public struct UDImage: Codable {
/// Url to the image
public var url: URL?
/// Width of the image
public var width: Int?
/// Height of the image
public var height: Int?
/// Create a UDImage object.
///
/// - Parameter json: JSON object
public init?(json: Data) {
let decoder = JSONDecoder()
guard let image = try? decoder.decode(UDImage.self, from: json) else {
return nil
}
self = image
}
}
// MARK: - Fields
public extension UDImage {
public enum fields {
case url
case width
case height
}
public static var allFields: [UDImage.fields] {
return [
.url,
.width,
.height
]
}
fileprivate enum CodingKeys: String, CodingKey {
case url = "url"
case width = "width"
case height = "height"
}
}
// MARK: - Fields: CustomStringConvertible
extension UDImage.fields: CustomStringConvertible {
public var description: String {
switch self {
case .url:
return UDImage.CodingKeys.url.stringValue
case .width:
return UDImage.CodingKeys.width.stringValue
case .height:
return UDImage.CodingKeys.height.stringValue
}
}
}
// MARK: - Query
public extension UDImage {
public static func generateQuery(fields: [UDImage.fields]) -> String {
guard fields.count > 0 else {
return ""
}
let fieldsStrings: [String] = fields.map { $0.description }
let request = Request(name: UDNanodegree.fields.heroImage(fields: []).description, fields: fieldsStrings)
return request.asGraphQLString
}
}
// MARK: - Equatable
extension UDImage: Equatable {
public static func ==(lhs: UDImage, rhs: UDImage) -> Bool {
return lhs.url == rhs.url
}
}
// MARK: - CustomStringConvertible
extension UDImage: CustomStringConvertible {
public var description: String {
return url?.absoluteString ?? "--"
}
}
// MARK: - CustomDebugStringConvertible
extension UDImage: CustomDebugStringConvertible {
public var debugDescription: String {
return """
Url: \(url?.absoluteString ?? "--")
Width: \(width?.description ?? "--")
Height: \(height?.description ?? "--")
"""
}
}