-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
Copy pathgetResourceLinkPath.ts
76 lines (69 loc) · 2.3 KB
/
getResourceLinkPath.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
import get from 'lodash/get';
import { linkToRecord } from '../../util';
import { Record } from '../../types';
export type LinkToFunctionType = (record: Record, reference: string) => string;
export type LinkToType = string | boolean | LinkToFunctionType;
interface Option {
source: string;
reference: string;
resource: string;
basePath?: string;
record?: Record;
link?: LinkToType;
/**
* @deprecated use link instead
*/
linkType?: LinkToType;
}
/**
* Get the link toward the referenced resource
*
* @example
*
* const linkPath = getResourceLinkPath({
* basePath: '/comments',
* link: 'edit',
* reference: 'users',
* record: {
* userId: 7
* },
* resource: 'comments',
* source: 'userId',
* }); // '/users/7'
*
* @param {Object} option
* @param {string} option.basePath basepath to current resource
* @param {string | false | LinkToFunctionType} option.link="edit" The link toward the referenced record. 'edit', 'show' or false for no link (default to edit). Alternatively a function that returns a string
* @param {string | false | LinkToFunctionType} [option.linkType] DEPRECATED : old name for link
* @param {string} option.reference The linked resource name
* @param {Object} option.record The current resource record
* @param {string} option.resource The current resource name
* @param {string} option.source The key of the linked resource identifier
*
* @returns {string | false} The link to the reference record
*/
const getResourceLinkPath = ({
resource,
source,
reference,
link = 'edit',
record = { id: '' },
basePath = `/${resource}`,
linkType,
}: Option): string | false => {
if (linkType !== undefined) {
console.warn(
"The 'linkType' prop is deprecated and should be named to 'link' in <ReferenceField />"
);
}
const sourceId = get(record, source);
const rootPath = basePath.replace(resource, reference);
const linkTo: LinkToType = linkType !== undefined ? linkType : link;
// Backward compatibility: keep linkType but with warning
return !linkTo
? false
: typeof linkTo === 'function'
? linkTo(record, reference)
: linkToRecord(rootPath, sourceId, linkTo as string);
};
export default getResourceLinkPath;