TT Client Library 1.0.0
C++ library for Tandem Tales clients.
Loading...
Searching...
No Matches
MessageFactory.h
1#pragma once
2
3#include <functional>
4#include <memory>
5#include <nlohmann/json.hpp>
6#include <tt/io/Message.h>
7
8#ifndef MESSAGEFACTORY_H
9#define MESSAGEFACTORY_H
10
11namespace tt {
21 public:
23 using Creator = std::function<std::unique_ptr<tt::Message>(const nlohmann::json&)>;
24
29 {
30 static MessageFactory factory;
31 return factory;
32 }
33
41 void registerType(const std::string& type, Creator creator)
42 {
43 creators_[type] = std::move(creator);
44 }
45
54 std::unique_ptr<tt::Message> create(const std::string& type, const nlohmann::json& j) const
55 {
56 auto it = creators_.find(type);
57 if (it == creators_.end()) {
58 return nullptr; // unknown type
59 }
60 return it->second(j);
61 }
62
63 private:
65 std::unordered_map<std::string, Creator> creators_;
66 };
67
75 template <typename T>
76 std::unique_ptr<Message> createFromJson(const nlohmann::json& j)
77 {
78 auto msg = std::make_unique<T>();
79 from_json(j, *msg);
80 return msg;
81 }
82
88}
89
90#endif
A helper class for deserializing messages.
Definition MessageFactory.h:20
std::unique_ptr< tt::Message > create(const std::string &type, const nlohmann::json &j) const
Looks up the creator of the desired type to deserialize json.
Definition MessageFactory.h:54
void registerType(const std::string &type, Creator creator)
Register a type with the message factory.
Definition MessageFactory.h:41
static MessageFactory & instance()
MessageFactory singleton.
Definition MessageFactory.h:28
std::function< std::unique_ptr< tt::Message >(const nlohmann::json &)> Creator
Type alias to simplify code.
Definition MessageFactory.h:23
Tandem Tales is a platform that enables short, paired storytelling exercises between two agents over ...
Definition Client.h:22
std::unique_ptr< Message > createFromJson(const nlohmann::json &j)
Creates a message of a specified type from JSON.
Definition MessageFactory.h:76
void registerMessageTypes()
Helper function to register all message types.
Definition MessageFactory.cpp:15