summaryrefslogtreecommitdiff
path: root/Juick/MessageFetcher.swift
blob: fd1f7f1454dbffe2d5b96992e283916906c6604f (plain) (blame)
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
//
//  MessageFetcher.swift
//  tst
//
//  Created by Vitaly Takmazov on 10.12.2019.
//  Copyright © 2019 com.juick. All rights reserved.
//

import Foundation
import Combine

class MessageFetcher: ObservableObject {
    
    typealias Feed = [MessageData]
    
    struct MessageData : Identifiable {
        var id : String {
            get {
                return "\(message.mid.stringValue)-\(message.rid?.intValue ?? 0)"
            }
        }
        var message : Message
    }
    
    @Published var state: LoadableState<Feed> = .loading
    
    init(url: String) {
        guard let _ = URL(string: url) else {
            state = .fetched(.failure(.error("Malformed API URL.")))
            return
        }
        
        AppDelegate.shared.api.pullNext(fromPath: url, params: nil) { (messages, error) in
            if let error = error {
                self.state = .fetched(.failure(.error(error.localizedDescription)))
                return
            }
            
            guard let messages = messages else {
                self.state = .fetched(.failure(.error("Malformed response data")))
                return
            }
            self.state = .fetched(.success(messages.map { return MessageData(message: $0) } ))
        }
    }
}