glean-core/ios/Glean/Metrics/ObjectMetric.swift (28 lines of code) (raw):

/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /// An object that can be serialized into JSON. /// /// Objects are defined by their structure in the metrics definition. public protocol ObjectSerialize: Codable, Decodable { func intoSerializedObject() -> String } extension Array: ObjectSerialize where Element: Codable { public func intoSerializedObject() -> String { let jsonEncoder = JSONEncoder() let jsonData = try! jsonEncoder.encode(self) let json = String(data: jsonData, encoding: String.Encoding.utf8)! return json } } /// This implements the developer facing API for the object metric type. /// /// Instances of this class type are automatically generated by the parsers at built time, /// allowing developers to record events that were previously registered in the metrics.yaml file. /// /// The Events API only exposes the `ObjectMetricType.set(obj:)` method, which takes care of validating the input /// data and making sure that limits are enforced. public class ObjectMetricType<K: ObjectSerialize> { let inner: ObjectMetric /// The public constructor used by automatically generated metrics. public init(_ meta: CommonMetricData) { self.inner = ObjectMetric(meta) } /// Sets to the associated structure. /// /// - parameters: /// * object: the object to set. public func set(_ object: K) { self.inner.setString(object.intoSerializedObject()) } /// Returns the stored value for testing purposes only. This function will attempt to await the /// last task (if any) writing to the the metric's storage engine before returning a value. /// /// - parameters: /// * pingName: represents the name of the ping to retrieve the metric for. /// Defaults to the first value in `sendInPings`. /// /// - returns: value of the stored metric decoded into the associated object /// or `nil` if nothing was recorded. public func testGetValue(_ pingName: String? = nil) -> K? { guard let data = self.inner.testGetValue(pingName) else { return nil } let jsonDecoder = JSONDecoder() return try! jsonDecoder.decode(K.self, from: Data(data.utf8)) } /// Returns the number of errors recorded for the given metric. /// /// - parameters: /// * errorType: The type of error recorded. /// /// - returns: The number of errors recorded for the metric for the given error type. public func testGetNumRecordedErrors(_ errorType: ErrorType) -> Int32 { return self.inner.testGetNumRecordedErrors(errorType) } }