Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Makes the code more readable via early returns / fatal errors in guards #35

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 22 additions & 22 deletions Sources/Core/SchemaLoader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,30 +25,30 @@ class FileSchemaLoader: SchemaLoader {
if let cachedValue = refs[schemaUrl] {
return cachedValue
}

// Load from local file
if let data = try? Data(contentsOf: URL(fileURLWithPath: schemaUrl.path)) {
if let jsonResult = try? JSONSerialization.jsonObject(with: data,
options: JSONSerialization.ReadingOptions.mutableContainers) {
if let jsonDict = jsonResult as? JSONObject {
let id = jsonDict["id"] as? String ?? ""
if id.hasSuffix(schemaUrl.lastPathComponent) == false {
fatalError("Invalid Schema: The value for the `id` (\(id) must end with the filename \(schemaUrl.lastPathComponent).")
}

if let schema = FileSchemaLoader.sharedPropertyLoader(jsonDict, schemaUrl) {
refs[schemaUrl] = schema
return schema
} else {
fatalError("Invalid Schema. Unable to parse schema at URL: \(schemaUrl)")
}
} else {
fatalError("Invalid Schema. Expected dictionary as the root object type for schema at URL: \(schemaUrl)")
}
} else {
fatalError("Invalid JSON. Unable to parse json at URL: \(schemaUrl)")
}
} else {
guard let data = try? Data(contentsOf: URL(fileURLWithPath: schemaUrl.path)) else {
fatalError("Error loading or parsing schema at URL: \(schemaUrl)")
}

guard let jsonResult = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) else {
fatalError("Invalid JSON. Unable to parse json at URL: \(schemaUrl)")
}

guard let jsonDict = jsonResult as? JSONObject else {
fatalError("Invalid Schema. Expected dictionary as the root object type for schema at URL: \(schemaUrl)")
}

let id = jsonDict["id"] as? String ?? ""
guard id.hasSuffix(schemaUrl.lastPathComponent) == true else {
fatalError("Invalid Schema: The value for the `id` (\(id) must end with the filename \(schemaUrl.lastPathComponent).")
}

guard let schema = FileSchemaLoader.sharedPropertyLoader(jsonDict, schemaUrl) else {
fatalError("Invalid Schema. Unable to parse schema at URL: \(schemaUrl)")
}

refs[schemaUrl] = schema
return schema
}
}