-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAwsServices.swift
More file actions
99 lines (79 loc) · 2.66 KB
/
AwsServices.swift
File metadata and controls
99 lines (79 loc) · 2.66 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//
// AwsServices.swift
// awsary
//
// Created by Tiago Rodrigues on 02/01/2023.
//
import Foundation
var fm = FileManager.default
var mainUrl: URL? = Bundle.main.url(forResource: "aws_services", withExtension: "json")
var lastRandom: awsService = awsService(id: 10, name: "DeepRacer", longName: "AWS DeepRacer", shortDesctiption: "DeepRacer", imageURL: "https://static.tig.pt/awsary/logos/Arch_AWS-DeepRacer_64.svg", youtube_id: "")
class AwsServices: ObservableObject {
@Published var services = [awsService]()
func getNameOfLastRandom() -> String {
return lastRandom.longName
}
func getLastRandom() -> awsService {
return lastRandom
}
func getRandomElement() -> awsService {
if services.isEmpty {
refresh()
}
guard let randomService = services.randomElement() else {
return lastRandom
}
lastRandom = randomService
return randomService
}
init() {
refresh()
}
private func servicesFromDocuments() -> [awsService] {
do {
let documentDirectory = try fm.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let documentURL = documentDirectory.appendingPathComponent("aws_services.json")
guard fm.fileExists(atPath: documentURL.path) else {
return []
}
return decodeData(pathName: documentURL)
} catch {
print("Failed to resolve documents directory for aws_services.json: \(error)")
return []
}
}
private func servicesFromBundle() -> [awsService] {
guard let bundleURL = mainUrl else {
print("Missing bundled aws_services.json")
return []
}
return decodeData(pathName: bundleURL)
}
private func decodeData(pathName: URL) -> [awsService] {
do {
let jsonData = try Data(contentsOf: pathName)
let decoder = JSONDecoder()
let decoded = try decoder.decode([awsService].self, from: jsonData)
if decoded.isEmpty {
print("Decoded zero services from \(pathName.lastPathComponent)")
}
return decoded
} catch {
print("Failed to decode aws_services.json from \(pathName): \(error)")
return []
}
}
func refresh() {
var loadedServices = servicesFromDocuments()
if loadedServices.isEmpty {
loadedServices = servicesFromBundle()
}
if loadedServices.isEmpty {
print("Falling back to last known service to prevent empty catalogue")
services = [lastRandom]
} else {
loadedServices.sort { $0.name < $1.name }
services = loadedServices
}
}
}