From 491e392af73be3ebfd928e80efc0514fd43b8e87 Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Thu, 16 Nov 2017 14:10:08 +0900 Subject: Simplify code that loads events from JSON arrays --- events/event.h | 41 +++++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 18 deletions(-) (limited to 'events') diff --git a/events/event.h b/events/event.h index c0c1b603..cc99b57b 100644 --- a/events/event.h +++ b/events/event.h @@ -63,6 +63,10 @@ namespace QMatrixClient // (and in most cases it will be a combination of other fields // instead of "content" field). + /** Create an event with proper type from a JSON object + * Use this factory to detect the type from the JSON object contents + * and create an event object of that type. + */ static Event* fromJson(const QJsonObject& obj); protected: @@ -77,26 +81,27 @@ namespace QMatrixClient Q_PROPERTY(QJsonObject contentJson READ contentJson CONSTANT) }; using EventType = Event::Type; - template - using EventsBatch = std::vector; - using Events = EventsBatch; - template > - inline BatchT makeEvents(const QJsonArray& objs) + template + class EventsBatch : public std::vector { - BatchT evs; - // The below line accommodates the difference in size types of - // STL and Qt containers. - evs.reserve(static_cast(objs.size())); - for (auto objValue: objs) - { - const auto o = objValue.toObject(); - auto e = BaseEventT::fromJson(o); - evs.push_back(e ? e : new BaseEventT(EventType::Unknown, o)); - } - return evs; - } + public: + void fromJson(const QJsonObject& container, const QString& node) + { + const auto objs = container.value(node).toArray(); + using size_type = typename std::vector::size_type; + // The below line accommodates the difference in size types of + // STL and Qt containers. + this->reserve(static_cast(objs.size())); + for (auto objValue: objs) + { + const auto o = objValue.toObject(); + auto e = EventT::fromJson(o); + this->push_back(e ? e : new EventT(EventType::Unknown, o)); + } + } + }; + using Events = EventsBatch; /** This class corresponds to m.room.* events */ class RoomEvent : public Event -- cgit v1.2.3