/
RemoteNotification.swift
68 lines (58 loc) · 2.15 KB
/
RemoteNotification.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
//
// RemoteNotification.swift
// SwiftSample
//
// Created by Mutsumi Kakuta on 2020/05/13.
// Copyright © 2020 Mutsumi Kakuta. All rights reserved.
//
import Foundation
struct RemoteNotification {
struct PayloadDataEntity: Decodable {
enum CodingKeys: String, CodingKey {
case transitionType = "transition_type"
case searchKeyword = "search_keyword"
case order
case productID = "product_id"
}
let transitionType: String
let searchKeyword: String?
let order: String?
let productID: String?
init(dictionary: [String: AnyObject]) throws {
self = try JSONDecoder().decode(PayloadDataEntity.self, from: JSONSerialization.data(withJSONObject: dictionary))
}
}
struct SearchResultsListEntity {
let searchKeyword: String
let order: String
}
struct ProductDetailEntity {
let productID: String
}
enum TransitionType: String {
case searchResultsList = "search_results_list"
case productDetail = "product_detail"
}
enum NotificationType {
case searchResultsList(SearchResultsListEntity)
case productDetail(ProductDetailEntity)
}
enum NotificationError: Error {
case invalidType
case invalidData
}
static func convert(from data: [String: AnyObject]) throws -> NotificationType {
let data = try PayloadDataEntity(dictionary: data)
guard let transitionType = TransitionType(rawValue: data.transitionType) else { throw NotificationError.invalidType }
switch transitionType {
case .searchResultsList:
guard let searchKeyword = data.searchKeyword, let order = data.order else { throw NotificationError.invalidData }
let entity = SearchResultsListEntity(searchKeyword: searchKeyword, order: order)
return .searchResultsList(entity)
case .productDetail:
guard let productID = data.productID else { throw NotificationError.invalidData }
let entity = ProductDetailEntity(productID: productID)
return .productDetail(entity)
}
}
}