diff options
| author | ha-dai <contact@haradai.net> | 2017-11-27 03:41:47 +0900 |
|---|---|---|
| committer | ha-dai <contact@haradai.net> | 2017-11-27 03:41:47 +0900 |
| commit | 6c75bc6d5188cbbf80fe1086fa0e8828f4edb873 (patch) | |
| tree | 3ffedcc3a06e53269e92d2990cf0b3bb247ac04a /src/web/app/common/scripts/api.ts | |
| parent | Merge branch 'master' of https://github.com/syuilo/misskey (diff) | |
| parent | Update dependencies :rocket: (diff) | |
| download | misskey-6c75bc6d5188cbbf80fe1086fa0e8828f4edb873.tar.gz misskey-6c75bc6d5188cbbf80fe1086fa0e8828f4edb873.tar.bz2 misskey-6c75bc6d5188cbbf80fe1086fa0e8828f4edb873.zip | |
Merge branch 'master' of github.com:syuilo/misskey
Diffstat (limited to 'src/web/app/common/scripts/api.ts')
| -rw-r--r-- | src/web/app/common/scripts/api.ts | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/src/web/app/common/scripts/api.ts b/src/web/app/common/scripts/api.ts new file mode 100644 index 0000000000..e62447b0a0 --- /dev/null +++ b/src/web/app/common/scripts/api.ts @@ -0,0 +1,46 @@ +/** + * API Request + */ + +declare const _API_URL_: string; + +let spinner = null; +let pending = 0; + +/** + * Send a request to API + * @param {string|Object} i Credential + * @param {string} endpoint Endpoint + * @param {any} [data={}] Data + * @return {Promise<any>} Response + */ +export default (i, endpoint, data = {}): Promise<{ [x: string]: any }> => { + if (++pending === 1) { + spinner = document.createElement('div'); + spinner.setAttribute('id', 'wait'); + document.body.appendChild(spinner); + } + + // Append the credential + if (i != null) (data as any).i = typeof i === 'object' ? i.token : i; + + return new Promise((resolve, reject) => { + // Send request + fetch(endpoint.indexOf('://') > -1 ? endpoint : `${_API_URL_}/${endpoint}`, { + method: 'POST', + body: JSON.stringify(data), + credentials: endpoint === 'signin' ? 'include' : 'omit' + }).then(res => { + if (--pending === 0) spinner.parentNode.removeChild(spinner); + if (res.status === 200) { + res.json().then(resolve); + } else if (res.status === 204) { + resolve(); + } else { + res.json().then(err => { + reject(err.error); + }); + } + }).catch(reject); + }); +}; |