|
1 | 1 | (function () { |
2 | | - var input = location.search.substring(1).split('/'); |
3 | | - var gistId = input[0]; |
4 | | - var fileName = input[1] || 'index.html'; |
| 2 | + document.getElementById('submit').onclick = function () { |
| 3 | + location.search = document.getElementById('gist_id').value + '/' |
| 4 | + + document.getElementById('file_name').value; |
| 5 | + } |
5 | 6 |
|
| 7 | + // 1. check query string |
| 8 | + var query = location.search.substring(1); |
| 9 | + if (query.length === 0) { |
| 10 | + return; |
| 11 | + } |
| 12 | + |
| 13 | + // 2. get gist id and file name |
| 14 | + query = query.split('/'); |
| 15 | + var gistId = query[0]; |
| 16 | + var fileName = query[1]; |
| 17 | + |
| 18 | + // 3. write data to blank |
| 19 | + document.getElementById('gist_id').value = gistId; |
| 20 | + document.getElementById('file_name').value = fileName; |
| 21 | + |
| 22 | + // 4-1. check gist id |
| 23 | + if (/^[0-9a-f]*$/g.test(gistId) === false) { |
| 24 | + console.error('Gist Id ' + gistId + ' is invalid') |
| 25 | + return; |
| 26 | + } |
| 27 | + |
| 28 | + // 4-2. check file name |
| 29 | + if (typeof fileName !== 'string' || fileName.length === 0) { |
| 30 | + console.error('File Name ' + fileName + ' is invalid'); |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + // 5. fetch data |
6 | 35 | fetch('https://api.github.com/gists/' + gistId) |
7 | 36 | .then(function (res) { |
8 | 37 | if (res.status !== 200) { |
9 | | - var err = new Error(gistId + ' is not found'); |
10 | | - err.code = 'ENOENT'; |
11 | | - throw err; |
| 38 | + throw new Error('Gist Id ' + gistId + ' is not exist'); |
12 | 39 | } |
13 | 40 | return res.json(); |
14 | 41 | }) |
15 | 42 | .then(function (info) { |
16 | 43 | if (info.files.hasOwnProperty(fileName) === false) { |
17 | | - var err = new Error(fileName + ' is not found'); |
18 | | - err.code = 'ENOENT'; |
19 | | - throw err; |
| 44 | + throw new Error('File ' + fileName + ' is not exist'); |
20 | 45 | } |
21 | 46 |
|
| 47 | + // 6. write data |
22 | 48 | var content = info.files[fileName].content; |
23 | 49 | document.write(content); |
24 | 50 | }) |
|
0 commit comments