-
Notifications
You must be signed in to change notification settings - Fork 36
/
fetch.ts
194 lines (174 loc) · 5.79 KB
/
fetch.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/**
* Pick list item fetching code
*/
import { f } from '../../utils/functools';
import type { R, RA } from '../../utils/types';
import { defined } from '../../utils/types';
import { sortFunction, toLowerCase } from '../../utils/utils';
import { fetchCollection, fetchRows } from '../DataModel/collection';
import type { SerializedResource } from '../DataModel/helperTypes';
import type { SpecifyResource } from '../DataModel/legacyTypes';
import { schema } from '../DataModel/schema';
import {
deserializeResource,
serializeResource,
} from '../DataModel/serializers';
import { strictGetTable } from '../DataModel/tables';
import type { PickList, PickListItem, Tables } from '../DataModel/types';
import { softFail } from '../Errors/Crash';
import { format } from '../Formatters/formatters';
import type { PickListItemSimple } from '../FormFields/ComboBox';
import { getCollectionPref } from '../InitialContext/remotePrefs';
import { hasTablePermission, hasToolPermission } from '../Permissions/helpers';
import {
createPickListItem,
getFrontEndPickLists,
PickListTypes,
unsafeGetPickLists,
} from './definitions';
const pickListFetchPromises: R<Promise<SpecifyResource<PickList> | undefined>> =
{};
export async function fetchPickList(
pickListName: string
): Promise<SpecifyResource<PickList> | undefined> {
pickListFetchPromises[pickListName] ??= unsafeFetchPickList(pickListName);
return pickListFetchPromises[pickListName];
}
async function unsafeFetchPickList(
pickListName: string
): Promise<SpecifyResource<PickList> | undefined> {
getFrontEndPickLists();
let pickList: SpecifyResource<PickList> | undefined =
unsafeGetPickLists()[pickListName];
if (pickList === undefined) {
if (
pickListName in unsafeGetPickLists() &&
unsafeGetPickLists()[pickListName] === undefined
)
// Pick list does not exist
return undefined;
if (!hasToolPermission('pickLists', 'read')) return undefined;
pickList = await rawFetchPickList(pickListName, true);
if (pickList === undefined)
pickList = await rawFetchPickList(pickListName, false);
unsafeGetPickLists()[pickListName] = pickList;
}
if (pickList === undefined) return undefined;
pickList.set('pickListItems', await fetchPickListItems(pickList));
return pickList;
}
const rawFetchPickList = async (
name: string,
domainFilter: boolean
): Promise<SpecifyResource<PickList> | undefined> =>
fetchCollection('PickList', {
name,
limit: 1,
domainFilter,
}).then(({ records }) => f.maybe(records[0], deserializeResource));
async function fetchPickListItems(
pickList: SpecifyResource<PickList>
): Promise<RA<SerializedResource<PickListItem>>> {
const type = (pickList?.get('type') as 0 | 1 | 2 | undefined) ?? 0;
let items;
const limit = Math.max(
0,
pickList.get('readOnly') ? pickList.get('sizeLimit') ?? 0 : 0
);
if (type === PickListTypes.TABLE)
items = await fetchFromTable(pickList, limit);
else if (type === PickListTypes.FIELDS)
items = await fetchFromField(pickList, limit);
else {
if (type !== PickListTypes.ITEMS)
softFail(new Error('Unknown picklist type'), { pickList });
return serializeResource(pickList).pickListItems ?? [];
}
return items.map(({ value, title }) => createPickListItem(value, title));
}
export const PickListSortType = {
NO_SORT: 0,
// Sort by "title" field
TITLE_SORT: 1,
// Sort by "ordinal" field
ORDINAL_SORT: 2,
};
/** From the table picklist */
async function fetchFromTable(
pickList: SpecifyResource<PickList>,
limit: number
): Promise<RA<PickListItemSimple>> {
const tableName = strictGetTable(pickList.get('tableName')).name;
if (!hasTablePermission(tableName, 'read')) return [];
const scopeTablePicklist = getCollectionPref(
'sp7_scope_table_picklists',
schema.domainLevelIds.collection
);
const { records } = await fetchCollection(tableName, {
domainFilter: scopeTablePicklist
? true
: !f.includes(Object.keys(schema.domainLevelIds), toLowerCase(tableName)),
limit,
});
return Promise.all(
records.map(async (record) =>
format(
deserializeResource(record),
pickList.get('formatter') ?? undefined,
true
).then((title) => ({
value: record.id.toString(),
title,
}))
)
);
}
/** From the field picklist */
async function fetchFromField(
pickList: SpecifyResource<PickList>,
limit: number
): Promise<RA<PickListItemSimple>> {
const tableName = defined(
pickList.get('tableName') ?? undefined,
'Unable to fetch pick list item as pick list table is not set'
);
const fieldName = defined(
pickList.get('fieldName') ?? undefined,
'Unable to fetch pick list items as pick list field is not set'
);
return fetchRows(tableName as keyof Tables, {
limit,
fields: { [fieldName]: ['string', 'number', 'boolean', 'null'] },
distinct: true,
domainFilter: true,
}).then((rows) =>
rows
.map((row) => row[fieldName] ?? '')
.map((value) => ({ value, title: value }))
);
}
/*
* TEST: make sure pick lists items are sorted properly everywhere (i.e, in the
* workbench)
* Sort pick list items and extract value and title fields
*/
export function getPickListItems(pickList: SpecifyResource<PickList>): RA<{
readonly value: string;
readonly title: string;
}> {
const items = serializeResource(pickList).pickListItems;
return (
pickList.get('sortType') === PickListSortType.TITLE_SORT
? Array.from(items).sort(sortFunction(({ title }) => title))
: pickList.get('sortType') === PickListSortType.ORDINAL_SORT
? Array.from(items).sort(sortFunction(({ ordinal }) => ordinal))
: items
).map(({ value, title }) => ({
value: value ?? title,
title: title ?? value,
}));
}
export const exportsForTests = {
unsafeFetchPickList,
fetchPickListItems,
};