headerのAuthorization部を変えれば、basicとoauth token を切り替えられる。
...
,auth ="Basic " + btoa(u+":"+p)
//,auth ="token a04f631c476b4b54e131XXXXXXXXXXXXXXXXXXX"
;//get token is https://github.com/settings/tokens
fetchの基本型
catchは復旧してresolveに戻さない限り呼び出し側が実装する。
let url=...
,option={method:'POST',mode:'cors',headers:{...}/*,body:{...}*/ }
;//method: 'HEAD' 'POST' 'PATCH' 'DELETE' 'GET' //mode: 'cors' 'no-cors'
return fetch(url,option).then(res=>res.text()) /*|res.json()|res.ok...*/
新規でgistを作ってアップロードする。
let up=(str)=>{
if(str.length==0) return Promise.reject('data is 0')
;
let u =window.prompt('u?'),p=window.prompt('p?')
if(!u || !p ) return Promise.reject('cancel')
;
let filename = str.slice(0,20),content=str,desc =new Date().toISOString()
,auth ="Basic " + btoa(u+":"+p)
//,auth ="token a04f631c476b4b54e131XXXXXXXXXXXXXXXXXXX"
;//get token is https://github.com/settings/tokens
return fetch("https://api.github.com/gists",{
method:"POST"
,mode:"cors"
,headers:{
"Authorization":auth
,'Accept': 'application/json'
,'Content-Type': 'application/json'
}
,body:JSON.stringify({
public: false
,description: desc
,files:{
[filename]:{content: content}
}
})
})
;
;//
}
最小のuiで
<button onclick="upgist()">upgist</button><br>
<textarea></textarea><br>
<pre></pre>
function upgist(){
const data=fn.q('textarea').value
,show =(d=>{fn.q('pre').textContent = JSON.stringify(d,null,2);return d})
Promise.resolve(data)
.then(up)
.then(fn.log)
.then(res=>res.json())
.then(show)
.catch(show)
;
}
全部
<button onclick="upgist()">upgist</button><br>
<textarea></textarea><br>
<pre></pre>
let fn={}
fn.q =(d=>document.querySelector(d))
fn.log=(d)=>{console.log(d);return d}
;
let up=(str)=>{
if(str.length==0) return Promise.reject('data is 0')
;
let u =window.prompt('u?'),p=window.prompt('p?')
if(!u || !p ) return Promise.reject('cancel')
;
let filename = str.slice(0,20),content=str,desc =new Date().toISOString()
,auth ="Basic " + btoa(u+":"+p)
//,auth ="token a04f631c476b4b54e131XXXXXXXXXXXXXXXXXXX"
;//get token is https://github.com/settings/tokens
return fetch("https://api.github.com/gists",{
method:"POST"
,mode:"cors"
,headers:{
"Authorization":auth
,'Accept': 'application/json'
,'Content-Type': 'application/json'
}
,body:JSON.stringify({
public: false
,description: desc
,files:{
[filename]:{content: content}
}
})
})
;
;//
}
;
function upgist(){
const data=fn.q('textarea').value
,show =(d=>{fn.q('pre').textContent = JSON.stringify(d,null,2);return d})
Promise.resolve(data)
.then(up)
.then(fn.log)
.then(res=>res.json())
.then(show)
.catch(show)
;
}