finnow/finnow-api/source/account/api.d

86 lines
2.5 KiB
D
Raw Permalink Normal View History

/**
* This module defines the API endpoints for dealing with Accounts directly,
* including any data-transfer objects that are needed.
*/
module account.api;
import handy_httpd;
import profile.service;
import account.model;
import util.money;
import util.json;
/// The data the API provides for an Account entity.
struct AccountResponse {
ulong id;
string createdAt;
bool archived;
string type;
string numberSuffix;
string name;
string currency;
string description;
static AccountResponse of(in Account account) {
AccountResponse r;
r.id = account.id;
r.createdAt = account.createdAt.toISOExtString();
r.archived = account.archived;
r.type = account.type.id;
r.numberSuffix = account.numberSuffix;
r.name = account.name;
r.currency = account.currency.code.dup;
r.description = account.description;
return r;
}
}
void handleGetAccounts(ref HttpRequestContext ctx) {
import std.algorithm;
import std.array;
auto ds = getProfileDataSource(ctx);
auto accounts = ds.getAccountRepository().findAll()
.map!(a => AccountResponse.of(a)).array;
writeJsonBody(ctx, accounts);
}
void handleGetAccount(ref HttpRequestContext ctx) {
ulong accountId = ctx.request.getPathParamAs!ulong("accountId");
auto ds = getProfileDataSource(ctx);
auto account = ds.getAccountRepository().findById(accountId)
.orElseThrow(() => new HttpStatusException(HttpStatus.NOT_FOUND));
writeJsonBody(ctx, AccountResponse.of(account));
}
// The data provided by a user to create a new account.
struct AccountCreationPayload {
string type;
string numberSuffix;
string name;
string currency;
string description;
}
void handleCreateAccount(ref HttpRequestContext ctx) {
auto ds = getProfileDataSource(ctx);
AccountCreationPayload payload = readJsonPayload!AccountCreationPayload(ctx);
// TODO: Validate the account creation payload.
AccountType type = AccountType.fromId(payload.type);
Currency currency = Currency.ofCode(payload.currency);
Account account = ds.getAccountRepository().insert(
type,
payload.numberSuffix,
payload.name,
currency,
payload.description
);
writeJsonBody(ctx, AccountResponse.of(account));
}
void handleDeleteAccount(ref HttpRequestContext ctx) {
ulong accountId = ctx.request.getPathParamAs!ulong("accountId");
auto ds = getProfileDataSource(ctx);
ds.getAccountRepository().deleteById(accountId);
}