Skip to content

Instantly share code, notes, and snippets.

@sanonz
Last active January 17, 2025 12:48
Show Gist options
  • Select an option

  • Save sanonz/bef20bc563a3dd8b99540d3f2fbda65d to your computer and use it in GitHub Desktop.

Select an option

Save sanonz/bef20bc563a3dd8b99540d3f2fbda65d to your computer and use it in GitHub Desktop.
JavaScript Snippets
import axios from 'axios';
const request = axios.create({
baseURL: `https://hacker-news.firebaseio.com/`,
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
},
});
let tokenRequest = null;
const authApi = 'auth/login';
const authRefreshApi = 'auth/refreshToken';
request.interceptors.request.use(function (config) {
// Inject token for header.
const auth = localStore.get('auth');
if (auth) {
config.headers.Token = auth.token;
}
// Ignore token of request.
const time = Date.now();
let api = trim(config.url.replace(config.baseURL, ''), '/');
if (
auth && auth.expire > time ||
api === authApi || api === authRefreshApi
) {
return config;
}
if (tokenRequest) {
return tokenRequest.then(() => {
const token = localStore.get('auth.token');
config.headers.Token = token;
return config;
});
}
// Fetch token
tokenRequest = request.post(/* auth ? authRefreshApi : */authApi)
.then(response => {
if (response.data.code === 0) {
const data = {
token: response.data.token,
expire: time + 1000 * 60 * 30, // half hour
};
config.headers.Token = data.token;
localStore.set('auth', data);
return config;
}
})
.finally(() => tokenRequest = null);
return tokenRequest;
}, function (error) {
return Promise.reject(error);
});
export default request;
console.log('\x1B[36m%s\x1B[0m', info); //cyan
console.log('\x1B[33m%s\x1b[0m:', path); //yellow
var styles = {
'bold' : ['\x1B[1m', '\x1B[22m'],
'italic' : ['\x1B[3m', '\x1B[23m'],
'underline' : ['\x1B[4m', '\x1B[24m'],
'inverse' : ['\x1B[7m', '\x1B[27m'],
'strikethrough' : ['\x1B[9m', '\x1B[29m'],
'white' : ['\x1B[37m', '\x1B[39m'],
'grey' : ['\x1B[90m', '\x1B[39m'],
'black' : ['\x1B[30m', '\x1B[39m'],
'blue' : ['\x1B[34m', '\x1B[39m'],
'cyan' : ['\x1B[36m', '\x1B[39m'],
'green' : ['\x1B[32m', '\x1B[39m'],
'magenta' : ['\x1B[35m', '\x1B[39m'],
'red' : ['\x1B[31m', '\x1B[39m'],
'yellow' : ['\x1B[33m', '\x1B[39m'],
'whiteBG' : ['\x1B[47m', '\x1B[49m'],
'greyBG' : ['\x1B[49;5;8m', '\x1B[49m'],
'blackBG' : ['\x1B[40m', '\x1B[49m'],
'blueBG' : ['\x1B[44m', '\x1B[49m'],
'cyanBG' : ['\x1B[46m', '\x1B[49m'],
'greenBG' : ['\x1B[42m', '\x1B[49m'],
'magentaBG' : ['\x1B[45m', '\x1B[49m'],
'redBG' : ['\x1B[41m', '\x1B[49m'],
'yellowBG' : ['\x1B[43m', '\x1B[49m']
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment