|
1 | 1 | import { createStore } from 'iiif-redux';
|
| 2 | +import { doesResourceExist } from 'iiif-redux/es/api/dereferenced'; |
| 3 | +import { iiifResourceRequestUnknownAsync } from 'iiif-redux/es/spaces/iiif-resource'; |
| 4 | +import { mappings as presentation2Mapping } from 'iiif-redux/es/api/2.x'; |
| 5 | +import { mappings as presentation3Mapping } from 'iiif-redux/es/api/3.x'; |
| 6 | +import DataLoader from 'dataloader'; |
2 | 7 |
|
3 | 8 | const store = createStore();
|
4 | 9 |
|
| 10 | +const iiifLoader = new DataLoader(keys => |
| 11 | + Promise.all( |
| 12 | + keys.map(id => store.dispatch(iiifResourceRequestUnknownAsync(id))) |
| 13 | + ) |
| 14 | +); |
| 15 | + |
| 16 | +function mapping(version) { |
| 17 | + if (version === 3) { |
| 18 | + return presentation3Mapping; |
| 19 | + } |
| 20 | + return presentation2Mapping; |
| 21 | +} |
| 22 | + |
| 23 | +function select(selector) { |
| 24 | + return selector(store.getState()); |
| 25 | +} |
| 26 | + |
| 27 | +async function loadResource(id, type) { |
| 28 | + return await iiifLoader.load(id); |
| 29 | +} |
| 30 | + |
| 31 | +const selectById = (id, type) => { |
| 32 | + return state => state.resources[type][id]; |
| 33 | +}; |
| 34 | + |
| 35 | +function resourceExists(id, type) { |
| 36 | + return select(doesResourceExist(selectById(id, type), type)); |
| 37 | +} |
| 38 | + |
| 39 | +function fieldExists(id, type, field) { |
| 40 | + const value = getFieldValue(id, type, field); |
| 41 | + |
| 42 | + return typeof value !== 'undefined' && value !== null; |
| 43 | +} |
| 44 | + |
| 45 | +function resourceDereferenced(id, type) {} |
| 46 | + |
| 47 | +function getFieldValue(id, type, field) { |
| 48 | + const version = getPresentationVersionFromResource( |
| 49 | + select(selectById(id, type)) |
| 50 | + ); |
| 51 | + const api = mapping(version)(selectById(id, type)); |
| 52 | + const singleField = api[field]; |
| 53 | + return select(singleField); |
| 54 | +} |
| 55 | + |
| 56 | +const combinedResolver = (id, type, field) => { |
| 57 | + if (!resourceExists(id, type)) { |
| 58 | + return loadResource(id, type).then(() => combinedResolver(id, type, field)); |
| 59 | + } |
| 60 | + if (!fieldExists(id, type, field)) { |
| 61 | + if (resourceDereferenced(id, type)) { |
| 62 | + return null; |
| 63 | + } |
| 64 | + return loadResource(id, type).then(() => combinedResolver(id, type, field)); |
| 65 | + } |
| 66 | + return getFieldValue(id, type, field); |
| 67 | +}; |
| 68 | + |
5 | 69 | const context = req => ({
|
6 | 70 | store,
|
7 | 71 | query: selector => {
|
8 | 72 | return selector(store.getState());
|
9 | 73 | },
|
| 74 | + combinedResolver, |
10 | 75 | });
|
11 | 76 |
|
12 | 77 | export default context;
|
0 commit comments