module util.data;

import handy_http_primitives;
import std.typecons;

Optional!T toOptional(T)(Nullable!T value) {
    if (value.isNull) {
        return Optional!T.empty;
    } else {
        return Optional!T.of(value.get);
    }
}

Nullable!T toNullable(T)(Optional!T value) {
    if (value.isNull) {
        return Nullable!(T)();
    } else {
        return Nullable!T(value.value);
    }
}

auto serializeOptional(T)(Optional!T value) {
    if (value.isNull) {
        return Nullable!T();
    }
    return Nullable!T(value.value);
}

ulong getPathParamOrThrow(T = ulong)(in ServerHttpRequest req, string name) {
    import handy_http_handlers.path_handler;
    import std.conv;
    foreach (param; getPathParams(req)) {
        if (param.name == name) {
            try {
                return param.value.to!T;
            } catch (ConvException e) {
                // Skip and throw if no params match.
            }
        }
    }
    // No params matched, so throw a NOT FOUND error.
    throw new HttpStatusException(HttpStatus.NOT_FOUND, "Missing required path parameter \"" ~ name ~ "\".");
}
