-
-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathdocs-store.js
More file actions
185 lines (159 loc) · 5.1 KB
/
Copy pathdocs-store.js
File metadata and controls
185 lines (159 loc) · 5.1 KB
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
/* global FastBoot */
import Service from '@ember/service';
import { getOwner } from '@ember/application';
import { tracked } from '@glimmer/tracking';
import { getRootURL } from 'ember-cli-addon-docs/-private/config';
import Project from '../models/project';
import Module from '../models/module';
import Class from '../models/class';
import Component from '../models/component';
const MODEL_CLASSES = {
project: Project,
module: Module,
class: Class,
component: Component,
};
/**
* A lightweight store that replaces ember-data for loading and caching
* documentation JSON. Fetches JSON API payloads from the build output
* and deserializes them into plain tracked objects.
*/
export default class DocsStoreService extends Service {
@tracked _records = {
project: {},
module: {},
class: {},
component: {},
};
_fetches = {};
async findRecord(type, id) {
let existing = this._records[type]?.[id];
if (existing) return existing;
if (type === 'project') {
if (!this._fetches[id]) {
this._fetches[id] = this._fetchProject(id);
}
return this._fetches[id];
}
return null;
}
peekRecord(type, id) {
return this._records[type]?.[id] || null;
}
peekAll(type) {
return Object.values(this._records[type] || {});
}
async _fetchProject(id) {
let payload;
let fastboot = getOwner(this).lookup('service:fastboot');
if (fastboot?.isFastBoot) {
// In FastBoot, use Node's http module to fetch from the local server
// that prember/fastboot is running
let http = FastBoot.require('http');
let request = fastboot.request;
// Derive host and protocol from the FastBoot/Node request in a standards-based way
let host =
(request &&
request.headers &&
(request.headers.host || request.headers.Host)) ||
request.host;
let protocol =
(request && request.protocol) ||
(request &&
request.headers &&
(request.headers['x-forwarded-proto'] ||
request.headers['X-Forwarded-Proto'])) ||
'http';
let url = `${protocol}://${host}/docs/${id}.json`;
let data = await new Promise((resolve, reject) => {
let req = http.get(url, (res) => {
res.setEncoding('utf8');
let body = '';
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
let statusCode = res.statusCode || 0;
if (statusCode >= 200 && statusCode < 300) {
resolve(body);
} else {
reject(
new Error(`Request to ${url} failed with status ${statusCode}`),
);
}
});
res.on('error', reject);
});
req.on('error', reject);
// Basic timeout so prember/fastboot failures don't hang indefinitely
req.setTimeout(10000, () => {
req.abort();
reject(new Error(`Request to ${url} timed out`));
});
});
payload = JSON.parse(data);
} else {
let namespace = `${getRootURL(this).replace(/\/$/, '')}/docs`;
let url = `${namespace}/${id}.json`;
let response;
try {
response = await fetch(url);
} catch (e) {
throw new Error(
`Network error while fetching ${url}: ${e && e.message}`,
);
}
if (!response.ok) {
throw new Error(
`Request to ${url} failed with status ${response.status}`,
);
}
payload = await response.json();
}
this._loadPayload(payload);
return this._records.project[id];
}
_loadPayload(payload) {
let allRecords = [];
// Collect data (can be single or array)
let dataItems = Array.isArray(payload.data) ? payload.data : [payload.data];
allRecords.push(...dataItems);
// Collect included
if (payload.included) {
allRecords.push(...payload.included);
}
// First pass: create all record instances with attributes
for (let raw of allRecords) {
let { type, id, attributes } = raw;
if (!MODEL_CLASSES[type]) continue;
let ModelClass = MODEL_CLASSES[type];
let record = new ModelClass();
record.id = id;
if (attributes) {
for (let [key, value] of Object.entries(attributes)) {
record[key] = value;
}
}
this._records[type][id] = record;
}
// Second pass: resolve relationships
for (let raw of allRecords) {
let { type, id, relationships } = raw;
if (!relationships || !this._records[type]?.[id]) continue;
let record = this._records[type][id];
for (let [key, rel] of Object.entries(relationships)) {
if (rel.data === null || rel.data === undefined) {
record[key] = null;
} else if (Array.isArray(rel.data)) {
record[key] = rel.data
.map((ref) => this._records[ref.type]?.[ref.id])
.filter(Boolean);
} else {
record[key] = this._records[rel.data.type]?.[rel.data.id] || null;
}
}
}
// Trigger reactivity update
this._records = { ...this._records };
}
}