|
1 | 1 | import Service from '@ember/service'; |
2 | 2 | import { getOwner } from '@ember/application'; |
3 | | -import { resolve } from 'rsvp'; |
4 | 3 | import fetch from 'fetch'; |
| 4 | +import { computed } from '@ember/object'; |
| 5 | +import { task } from 'ember-concurrency'; |
5 | 6 |
|
6 | 7 | export default Service.extend({ |
7 | 8 | current: null, |
8 | 9 | root: null, |
9 | 10 |
|
10 | | - init() { |
11 | | - this._super(...arguments); |
12 | | - |
| 11 | + _loadAvailableVersions: task(function*() { |
13 | 12 | let { rootURL } = getOwner(this).resolveRegistration('config:environment'); |
14 | 13 | let slash = rootURL.indexOf('/', 1); |
15 | 14 |
|
16 | 15 | // TODO deal with apps deployed to custom domains, so their pathnames don't have a leading |
17 | 16 | // segmenet for the project name. This will impact this service and the 404 page. |
18 | 17 | this.set('root', rootURL.slice(0, slash)); |
| 18 | + let currentFromURL = rootURL.substring(slash + 1).replace(/\/$/, ''); |
| 19 | + this.set('current', currentFromURL || 'latest'); // dev-time guard. Think of a better way? |
19 | 20 |
|
20 | | - if (slash === -1) { |
21 | | - this.set('current', 'development'); |
22 | | - this.set('_versionsPromise', resolve([{ name: 'development', path: '' }])); |
23 | | - } else { |
24 | | - this.set('current', rootURL.substring(slash + 1).replace(/\/$/, '')); |
25 | | - this.set('_versionsPromise', fetch(`${this.get('root')}/versions.json`) |
26 | | - .then(result => result.json()) |
27 | | - .then(json => Object.keys(json).map(key => json[key]))); |
28 | | - } |
29 | | - }, |
| 21 | + let response = yield fetch(`${this.get('root')}/versions.json`); |
| 22 | + let json = yield response.json(); |
| 23 | + |
| 24 | + this.set('versions', Object.keys(json).map(key => { |
| 25 | + let version = json[key]; |
| 26 | + version.truncatedSha = version.sha.substr(0,5); |
| 27 | + |
| 28 | + return version; |
| 29 | + })); |
| 30 | + }), |
30 | 31 |
|
31 | 32 | redirectTo(version) { |
32 | 33 | window.location.href = `${this.get('root')}/${version.path || version}`; |
33 | 34 | }, |
34 | 35 |
|
35 | | - getAvailableVersions() { |
36 | | - return this.get('_versionsPromise'); |
37 | | - } |
| 36 | + loadAvailableVersions() { |
| 37 | + return this.get('_loadAvailableVersions').perform(); |
| 38 | + }, |
| 39 | + |
| 40 | + currentVersion: computed('versions.[]', function() { |
| 41 | + let versions = this.get('versions'); |
| 42 | + |
| 43 | + if (versions) { |
| 44 | + return versions.find(version => version.name === this.get('current')); |
| 45 | + } |
| 46 | + }) |
| 47 | + |
38 | 48 | }); |
0 commit comments