-
Notifications
You must be signed in to change notification settings - Fork 232
Expand file tree
/
Copy pathChannelListQueryDTO.swift
More file actions
79 lines (63 loc) · 2.45 KB
/
ChannelListQueryDTO.swift
File metadata and controls
79 lines (63 loc) · 2.45 KB
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
//
// Copyright © 2026 Stream.io Inc. All rights reserved.
//
import CoreData
@objc(ChannelListQueryDTO)
class ChannelListQueryDTO: NSManagedObject {
/// Unique identifier of the query/
@NSManaged var filterHash: String
/// Serialized `Filter` JSON which can be used in cases the query needs to be repeated, i.e. for newly created channels.
@NSManaged var filterJSONData: Data
// MARK: - Relationships
@NSManaged var channels: Set<ChannelDTO>
static func load(filterHash: String, context: NSManagedObjectContext) -> ChannelListQueryDTO? {
load(
keyPath: #keyPath(ChannelListQueryDTO.filterHash),
equalTo: filterHash,
context: context
).first
}
/// The fetch request that returns all existed queries from the database.
static var allQueriesFetchRequest: NSFetchRequest<ChannelListQueryDTO> {
let request = NSFetchRequest<ChannelListQueryDTO>(entityName: ChannelListQueryDTO.entityName)
request.sortDescriptors = [
NSSortDescriptor(keyPath: \ChannelListQueryDTO.filterHash, ascending: false)
]
return request
}
}
extension NSManagedObjectContext {
func channelListQuery(_ query: ChannelListQuery) -> ChannelListQueryDTO? {
ChannelListQueryDTO.load(filterHash: query.queryHash, context: self)
}
func saveQuery(query: ChannelListQuery) -> ChannelListQueryDTO {
if let existingDTO = channelListQuery(query) {
return existingDTO
}
let request = ChannelListQueryDTO.fetchRequest(
keyPath: #keyPath(ChannelListQueryDTO.filterHash),
equalTo: query.queryHash
)
let newDTO = NSEntityDescription.insertNewObject(into: self, for: request)
newDTO.filterHash = query.queryHash
let jsonData: Data
do {
jsonData = try JSONEncoder.default.encode(query.filter)
} catch {
log.error("Failed encoding query Filter data with error: \(error).")
jsonData = Data()
}
newDTO.filterJSONData = jsonData
return newDTO
}
func loadAllChannelListQueries() -> [ChannelListQueryDTO] {
let queries: [ChannelListQueryDTO]
do {
queries = try fetch(ChannelListQueryDTO.allQueriesFetchRequest)
} catch {
log.error("Failed to load channel list queries from the database: \(error).")
queries = []
}
return queries
}
}