RESTful Color Palette Server▲
Sélectionnez
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef UTILS_H
#define UTILS_H
#include <QtCore/QFile>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonObject>
#include <QtCore/QList>
#include <QtCore/QPair>
#include <QtHttpServer/QtHttpServer>
#include <optional>
static
std::
optional&
lt;QByteArray&
gt; readFileToByteArray(const
QString &
amp;path)
{
QFile file(path);
if
(!
file.open(QIODevice::
ReadOnly |
QIODevice::
Text))
return
std::
nullopt;
return
file.readAll();
}
static
std::
optional&
lt;QJsonArray&
gt; byteArrayToJsonArray(const
QByteArray &
amp;arr)
{
QJsonParseError err;
const
auto
json =
QJsonDocument::
fromJson(arr, &
amp;err);
if
(err.error ||
!
json.isArray())
return
std::
nullopt;
return
json.array();
}
static
std::
optional&
lt;QJsonObject&
gt; byteArrayToJsonObject(const
QByteArray &
amp;arr)
{
QJsonParseError err;
const
auto
json =
QJsonDocument::
fromJson(arr, &
amp;err);
if
(err.error ||
!
json.isObject())
return
std::
nullopt;
return
json.object();
}
template
&
lt;typename
T&
gt;
static
IdMap&
lt;T&
gt; tryLoadFromFile(const
FromJsonFactory&
lt;T&
gt; &
amp;itemFactory, const
QString &
amp;path)
{
const
auto
maybeBytes =
readFileToByteArray(path);
if
(maybeBytes) {
const
auto
maybeArray =
byteArrayToJsonArray(*
maybeBytes);
if
(maybeArray) {
return
IdMap&
lt;T&
gt;(itemFactory, *
maybeArray);
}
else
{
qDebug() &
lt;&
lt; &
quot;Content of &
quot; &
lt;&
lt; path &
lt;&
lt; &
quot; is not
json array.&
quot;;
}
}
else
{
qDebug() &
lt;&
lt; &
quot;Reading file &
quot; &
lt;&
lt; path &
lt;&
lt; &
quot; failed.&
quot;;
}
return
IdMap&
lt;T&
gt;();
}
static
QByteArray getValueFromHeader(const
QList&
lt;QPair&
lt;QByteArray, QByteArray&
gt;&
gt; &
amp;headers,
const
QString &
amp;keyToFind)
{
for
(const
auto
&
amp;[key, value] : headers) {
if
(key ==
keyToFind) {
return
value;
}
}
return
QByteArray();
}
static
std::
optional&
lt;QString&
gt; getTokenFromRequest(const
QHttpServerRequest &
amp;request)
{
std::
optional&
lt;QString&
gt; token;
if
(auto
bytes =
getValueFromHeader(request.headers(), &
quot;TOKEN&
quot;); !
bytes.isEmpty()) {
token =
bytes;
}
return
token;
}
#endif
// UTILS_H