PleromaConfigDB: implement .getIn

This commit is contained in:
Alex Gleason 2024-11-14 19:54:29 -06:00
parent 3e27e902d5
commit 55f50ba93d
No known key found for this signature in database
GPG key ID: 7211D1F99744FBB7
2 changed files with 57 additions and 5 deletions

View file

@ -5,10 +5,23 @@ import data from '~/fixtures/config-db.json' with { type: 'json' };
import { PleromaConfig } from '@/schemas/pleroma-api.ts';
import { PleromaConfigDB } from '@/utils/PleromaConfigDB.ts';
Deno.test('PleromaConfigDB', () => {
const configs = new PleromaConfigDB(data.configs as PleromaConfig[]);
Deno.test('PleromaConfigDB.getIn', () => {
const configDB = new PleromaConfigDB(data.configs as PleromaConfig[]);
const frontendConfigurations = configs.get(':pleroma', ':frontend_configurations');
assertEquals(
configDB.get(':pleroma', ':frontend_configurations')?.value,
configDB.getIn(':pleroma', ':frontend_configurations'),
);
assertEquals((frontendConfigurations as any).value[1].tuple[0], ':soapbox_fe');
assertEquals(configDB.getIn(':pleroma', ':frontend_configurations', ':bleroma'), undefined);
assertEquals(
configDB.getIn(':pleroma', ':frontend_configurations', ':soapbox_fe', 'colors', 'primary', '500'),
'#1ca82b',
);
assertEquals(
configDB.getIn(':pleroma', ':frontend_configurations', ':soapbox_fe', 'colors', 'primary', '99999999'),
undefined,
);
});

View file

@ -1,4 +1,4 @@
import type { PleromaConfig } from '@/schemas/pleroma-api.ts';
import type { ElixirTuple, ElixirValue, PleromaConfig } from '@/schemas/pleroma-api.ts';
export class PleromaConfigDB {
constructor(private configs: PleromaConfig[]) {}
@ -7,6 +7,34 @@ export class PleromaConfigDB {
return this.configs.find((c) => c.group === group && c.key === key);
}
getIn(group: string, key: string, ...paths: string[]): ElixirValue | undefined {
const config = this.get(group, key);
if (!config) return undefined;
let value = config.value;
for (const path of paths) {
if (Array.isArray(value)) {
const tuple = value.find((item): item is ElixirTuple => {
return PleromaConfigDB.isTuple(item) && item.tuple[0] === path;
});
if (tuple) {
value = tuple.tuple[1];
} else {
return;
}
} else if (PleromaConfigDB.isTuple(value) && value.tuple[0] === path) {
value = value.tuple[1];
} else if (!PleromaConfigDB.isTuple(value) && value && typeof value === 'object' && path in value) {
value = value[path];
} else {
return;
}
}
return value;
}
set(group: string, key: string, value: PleromaConfig): void {
const index = this.configs.findIndex((c) => c.group === group && c.key === key);
if (index === -1) {
@ -25,4 +53,15 @@ export class PleromaConfigDB {
toJSON(): PleromaConfig[] {
return this.configs;
}
private static isTuple(value: ElixirValue): value is ElixirTuple {
return Boolean(
value &&
typeof value === 'object' &&
'tuple' in value &&
Array.isArray(value.tuple) &&
value.tuple.length === 2 &&
typeof value.tuple[0] === 'string',
);
}
}