75 lines
2.0 KiB
TypeScript
75 lines
2.0 KiB
TypeScript
import type {
|
|
MarketApiFailureReason,
|
|
MarketRecord,
|
|
MarketRowSnapshot
|
|
} from "./types";
|
|
import type { AfterSearchRates } from "./types";
|
|
|
|
export function createMarketResultStore() {
|
|
const records = new Map<string, MarketRecord>();
|
|
|
|
return {
|
|
getRecord(authorId: string) {
|
|
return records.get(authorId) ?? null;
|
|
},
|
|
listRecords() {
|
|
return Array.from(records.values());
|
|
},
|
|
setAuthorFailed(authorId: string, reason: MarketApiFailureReason) {
|
|
const existingRecord = ensureRecord(authorId);
|
|
existingRecord.status = "failed";
|
|
existingRecord.failureReason = reason;
|
|
},
|
|
setAuthorLoading(authorId: string) {
|
|
const existingRecord = ensureRecord(authorId);
|
|
existingRecord.status = "loading";
|
|
delete existingRecord.failureReason;
|
|
},
|
|
setAuthorSuccess(authorId: string, rates: AfterSearchRates) {
|
|
const existingRecord = ensureRecord(authorId);
|
|
existingRecord.status = "success";
|
|
existingRecord.rates = {
|
|
...existingRecord.rates,
|
|
...rates
|
|
};
|
|
delete existingRecord.failureReason;
|
|
},
|
|
upsertMarketRow(row: MarketRowSnapshot) {
|
|
const existingRecord = records.get(row.authorId);
|
|
if (existingRecord) {
|
|
existingRecord.hasDirectRatesSource =
|
|
existingRecord.hasDirectRatesSource || row.hasDirectRatesSource;
|
|
if (row.rates) {
|
|
existingRecord.rates = {
|
|
...existingRecord.rates,
|
|
...row.rates
|
|
};
|
|
}
|
|
return existingRecord;
|
|
}
|
|
|
|
const nextRecord: MarketRecord = {
|
|
...row,
|
|
status: "idle"
|
|
};
|
|
records.set(row.authorId, nextRecord);
|
|
return nextRecord;
|
|
}
|
|
};
|
|
|
|
function ensureRecord(authorId: string): MarketRecord {
|
|
const existingRecord = records.get(authorId);
|
|
if (existingRecord) {
|
|
return existingRecord;
|
|
}
|
|
|
|
const nextRecord: MarketRecord = {
|
|
authorId,
|
|
authorName: authorId,
|
|
status: "idle"
|
|
};
|
|
records.set(authorId, nextRecord);
|
|
return nextRecord;
|
|
}
|
|
}
|