Skip to content
Merged
Show file tree
Hide file tree
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
41 changes: 41 additions & 0 deletions Sources/FCM/FCMError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
public struct GoogleError: Error, Decodable {
public let code: Int
public let message: String
public let status: String
public let fcmError: FCMError?

private enum TopLevelCodingKeys: String, CodingKey {
case error
}

private enum CodingKeys: String, CodingKey {
case code, message, status, details
}

public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: TopLevelCodingKeys.self)
.nestedContainer(keyedBy: CodingKeys.self, forKey: .error)

code = try container.decode(Int.self, forKey: .code)
message = try container.decode(String.self, forKey: .message)
status = try container.decode(String.self, forKey: .status)

var details = try container.nestedUnkeyedContainer(forKey: .details)
fcmError = try? details.decode(FCMError.self)
}
}

public struct FCMError: Error, Decodable {
public let errorCode: ErrorCode

public enum ErrorCode: String, Decodable {
case unspecified = "UNSPECIFIED_ERROR"
case invalid = "INVALID_ARGUMENT"
case unregistered = "UNREGISTERED"
case senderIDMismatch = "SENDER_ID_MISMATCH"
case quotaExceeded = "QUOTA_EXCEEDED"
case apnsAuth = "APNS_AUTH_ERROR"
case unavailable = "UNAVAILABLE"
case `internal` = "INTERNAL"
}
}
21 changes: 13 additions & 8 deletions Sources/FCM/Helpers/FCM+SendMessage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,23 @@ extension FCM {
let payload = Payload(validate_only: false, message: message)
try req.content.encode(payload, as: .json)
}.map { res in
struct Result: Codable {
var name: String
}
guard let data = res.http.body.data else {
throw Abort(.notFound, reason: "Data not found")
}
do {
let result = try JSONDecoder().decode(Result.self, from: data)
return result.name
} catch {
throw Abort(.internalServerError, reason: String(data: data, encoding: .utf8) ?? "Unable to decode Firebase response")

guard 200 ..< 300 ~= res.http.status.code else {
if let googleError = try? res.content.syncDecode(GoogleError.self) {
throw googleError
} else {
let reason = String(data: data, encoding: .utf8) ?? "Unable to decode Firebase response"
throw Abort(.internalServerError, reason: reason)
}
}

struct Result: Codable {
var name: String
}
return try res.content.syncDecode(Result.self).name
}
}
}
Expand Down