-
Notifications
You must be signed in to change notification settings - Fork 2
/
Resource.js
322 lines (294 loc) · 8.01 KB
/
Resource.js
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
class Resource {
/**
* Model representing the response from a standard JSON:API
* @param {object} res
*/
constructor (raw, spider, config) {
this.raw = raw
this.data = this.getData(raw)
this.self = this.raw.links.self.href
this.config = config
this.spider = spider
// Internal "private" properties
this._path = false
this._entity = false
this._id = false
this._slugs = false
this._transformedFields = false
this._transformed = false
this._transformerConfig = {}
this._relationshipCrawlers = false
this._relationships = this.isResource() ? (this.data.relationships || {}) : {}
this._attributes = this.isResource() ? (this.data.attributes || {}) : {}
}
/**
* Get the data from our raw input.
* @return {object}
*/
getData (input) {
if (input.data && input.data.type && input.data.id) {
return input.data
}
if (input.type && input.id) {
return input
}
if (input.data && Array.isArray(input.data)) {
return input.data
}
return {}
}
/**
* Checks if the current resource is a collection or a single resource.
* @return {boolean}
*/
isCollection () {
return Array.isArray(this.data)
}
/**
* Determines if this resource is an actual resource (could be a collection
* or null)
* @return {boolean}
*/
isResource () {
const type = typeof this.data
return type === 'object' && !!this.data
}
/**
* Checks if this resource is empty.
* @return {boolean}
*/
isNull () {
return this.data === null
}
/**
* Returns the entity type. (Drupal specific)
* @return {string|boolean}
*/
entity () {
if (!this._entity && !this.isCollection()) {
this._entity = this.data.type.split('--')[0]
}
return this._entity
}
/**
* Fetch the resource bundle type. (Drupal specific)
* @return {string|boolean}
*/
bundle () {
if (!this._bundle && !this.isCollection()) {
this._bundle = this.data.type.split('--')[1]
}
return this._bundle
}
/**
* Get the actual ID of the given resource (Drupal specific)
* @return {string|boolean}
*/
id () {
if (!this._id && !this.isCollection()) {
const key = Object.keys(this.data.attributes).find(k => /^drupal_internal__[ntfm]?id/.test(k))
this._id = this.data.attributes[key]
}
return this._id
}
/**
* The URL "path" of a given resource. If it has an alias use that.
* @return {array}
*/
slugPaths () {
if (!this._slugs) {
this._slugs = []
if (this.entity() === 'node') {
if (this.data.attributes.path && this.data.attributes.path.alias) {
this._slugs.push(decodeURIComponent(this.data.attributes.path.alias))
}
this._slugs.push(`/node/${this.id()}`)
}
else if (this.entity() === 'taxonomy_term') {
if (this.data.attributes.path && this.data.attributes.path.alias) {
this._slugs.push(decodeURIComponent(this.data.attributes.path.alias))
}
this._slugs.push(`/taxonomy/term/${this.id()}`)
}
}
return this._slugs
}
/**
* Calculate the path of the current resource.
* @return {string}
*/
path () {
if (!this._path) {
if (!this.isCollection()) {
this._path = this.dataToUrl(this.data)
} else {
this._path = this.relativeUrl(this.self)
}
}
return this._path
}
/**
* Given a big-ol JSON:API style URL, clean it up to be relative and nice.
* @param {string|object}
* @return {string|boolean}
*/
relativeUrl (href) {
if (typeof href === 'string') {
const url = new URL(href)
return '/' + url.pathname.replace(/^\/jsonapi\//, '') + (url.search ? `${decodeURIComponent(url.search)}` : '')
} else if (typeof href === 'object' && Array.isArray(href.data) && href.data.length && href.data[0].id) {
return this.dataToUrl(href.data[0])
}
return false
}
/**
* Convert object data to a url.
* @param {object} data
*/
dataToUrl (data) {
return '/' + data.type.replace('--', '/') + '/' + data.id
}
/**
* Retrieve resources of each collection item.
* @return {array} Instances of each resource.
*/
resources () {
if (this.isCollection()) {
if (!this._resources) {
this.spider.emit('collection-index', { collection: this })
this._resources = this.data.map(resource => new Resource(resource, this.spider, this.config))
}
return this._resources
}
return [this]
}
/**
* Return the attached relationships (unloaded entities)
* @return {object}
*/
relationships () {
return this._relationships
}
/**
* Sets an internal promise that resolves when all pending relationships
* have been crawled (not necessarily output)
* @param {Promise} crawlPromise
* @return {Resource}
*/
setRelationshipCrawlers (crawlPromise) {
this._relationshipCrawlers = crawlPromise
return this
}
/**
* The relationship crawlers promise that should resolve when all of this
* resource's relationships are loaded.
* @return {Promise}
*/
relationshipCrawlers () {
return this._relationshipCrawlers
}
/**
* Return the attached attributes (generally node or field data)
* @return {object}
*/
attributes () {
return this._attributes
}
/**
* Parse and return all relevant related resource paths.
* @return {array} List of relationships.
*/
relationshipUrls () {
if (!this.isCollection()) {
const urls = [...this.parseRelationshipUrls(
Object.keys(this._relationships)
.filter(k => this.config.relationships.some(r => r.test(k)))
.map(k => this._relationships[k])
)]
return urls
}
return []
}
/**
* Given an array or object, recursively seek out all relationship.
* @param {array|object} set
* @return {Set}
*/
parseRelationshipUrls (items) {
const isRelationship = i => typeof i === 'object' && i && !Array.isArray(i) && i.type && i.id && i.type.indexOf('--') > 1
if (isRelationship(items)) {
return new Set([this.dataToUrl(items)])
}
if (typeof items === 'object' && !!items) {
items = (!Array.isArray(items)) ? Object.values(items) : items
return items.reduce((set, item) => new Set([...set, ...this.parseRelationshipUrls(item)]), new Set())
}
return new Set()
}
/**
* Checks if there is an additional collection page.
* @return {boolean}
*/
hasNextPage () {
return this.isCollection() && this.raw.links && this.raw.links.next
}
/**
* For collections that are paginated, this retrieves the next pagination url.
* @return {string}
*/
nextPageUrl () {
if (this.hasNextPage()) {
return this.relativeUrl(this.raw.links.next.href)
}
}
/**
* Set the configuration for transforming this resource.
* @param {object}
* @return Resource
*/
setTransformerConfig (config) {
this._transformerConfig = config
return this
}
/**
* Returns the configuration for transforming this resource.
* @return {object}
*/
transformerConfig () {
return this._transformerConfig
}
/**
* Set the transformed fields of this resource.
* @param {object}
* @return Resource
*/
setTransformedFields (fields) {
this._transformedFields = fields
return this
}
/**
* Returns the transformed fields of this resource.
* @return {object}
*/
transformedFields () {
return this._transformedFields
}
/**
* Set the final transformed data property.
* @param {object} transformed JSON.stringify ready object representing this resource.
* @return {Resource}
*/
setTransformedData (transformed) {
this._transformed = transformed
}
/**
* Return the transformed data that represents this resource. This must be
* set using `setTransformedData` from an external source. The Resource class
* does not contain any transformers.
* @return {object}
*/
transformedData () {
return this._transformed ? this._transformed : this.data
}
}
module.exports = Resource