Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.92 KB | None | 0 0
  1. import Vue from 'vue';
  2. import VueAxios from 'vue-axios';
  3. import Axios from 'axios';
  4. import moment from 'moment';
  5. import QS from 'qs';
  6. import Router from './router';
  7. import Y from '../helper/y';
  8.  
  9. Vue.use(VueAxios, Axios);
  10.  
  11. Axios.defaults.timeout = 10000;
  12.  
  13. const Ajax = new Vue({
  14. router: Router,
  15. computed: {
  16. http() {
  17. return this._.mapKeys(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD'], this._.toLower);
  18. },
  19. oauthTokenTypes() {
  20. return this._.mapKeys(['Bearer'], this._.toLower);
  21. },
  22. oauthGrantTypes() {
  23. return this._.mapKeys(['password', 'refresh_token'], this._.camelCase);
  24. },
  25. oauthStore() {
  26. return this.$store.getters.oauth || {};
  27. },
  28. oauthConfig() {
  29. return this.$config.get('oauth', {});
  30. },
  31. oauthTokenEndpoint: () => 'oauth/v2/token',
  32. impersonateEndPoint: () => 'api/private/impersonate',
  33. },
  34. data() {
  35. return {
  36. pendingRefresh: false,
  37. cancelToken: null,
  38. };
  39. },
  40. created() {
  41. this.cancel();
  42. },
  43. methods: {
  44. getUploadsUri(location) {
  45. return this.url(this.build(location), true);
  46. },
  47. url(config, withoutEndpoint = false) {
  48. let url = _.isObject(config) ? config.url : config;
  49. const endPoint = withoutEndpoint ? '/' : (this.$config.endpoint || '');
  50. if (url && url.indexOf('://') === -1) {
  51. url = `${this.$config.host}${endPoint}${url}`;
  52. }
  53. return url;
  54. },
  55. encode(input) {
  56. const format = (stack, key) => (stack ? `${stack}[${key}]` : key);
  57. // const Y = f => (...args) => f(Y(f))(...args);
  58. return Y(next => (form, data, stack = null) => {
  59. if (this._.isObject(data)) {
  60. this._.forOwn(data, (value, key) => {
  61. if (this._.isObject(value)) {
  62. if (this._.isBlob(value)) {
  63. const type = value.type.split('/').slice(-1).join();
  64. form.append(format(stack, key), value, value.name || `${key}.${type}`);
  65. } else if (this._.isArray(value)) {
  66. value.forEach(subValue => form.append(`${format(stack, key)}[]`, subValue));
  67. } else {
  68. next(form, value, format(stack, key));
  69. }
  70. } else {
  71. form.append(format(stack, key), value);
  72. }
  73. });
  74. }
  75. return form;
  76. })(new FormData(), this._.isString(input) ? QS.parse(input) : input);
  77. },
  78. sync() {
  79. this.wait = true;
  80. return this;
  81. },
  82. build(url, method, data = {}, config = {}) {
  83. return this._.extend(config, { url, method, data });
  84. },
  85. cancel(message) {
  86. if (this.cancelToken) {
  87. this.cancelToken.cancel(message);
  88. }
  89. this.cancelToken = this.$http.CancelToken.source();
  90. },
  91. publicRequest(url = '/', method = this.http.get, data = {}, config = {}) {
  92. const conf = this._.merge({
  93. method,
  94. url,
  95. data,
  96. }, config);
  97. conf.url = this.url(conf);
  98. return this.$http.request(conf).then(response => response.data);
  99. },
  100. get(url, data, config) {
  101. return this.request(this.build(url, this.http.get, data, config));
  102. },
  103. post(url, data, config) {
  104. return this.request(this.build(url, this.http.post, data, config));
  105. },
  106. put(url, data, config) {
  107. return this.request(this.build(url, this.http.put, data, config));
  108. },
  109. patch(url, data, config) {
  110. return this.request(this.build(url, this.http.patch, data, config));
  111. },
  112. delete(url, data, config) {
  113. return this.request(this.build(url, this.http.delete, data, config));
  114. },
  115. head(url, data, config) {
  116. return this.request(this.build(url, this.http.head, data, config));
  117. },
  118. redirect(uri = '/') {
  119. window.location.href = uri;
  120. },
  121. impersonate(userEmail = null, routeRedirect = null) {
  122. const redirect = () => {
  123. if (routeRedirect) {
  124. this.$router.push(routeRedirect);
  125. }
  126. };
  127.  
  128. if (!userEmail) {
  129. const oauth = JSON.parse(JSON.stringify(this.$store.getters.get.oauthUsurpator));
  130. this.set({ oauth, oauthUsurpator: null });
  131. return Promise.resolve().then(redirect);
  132. }
  133.  
  134. return this.get(`${this.impersonateEndPoint}/${userEmail}`).then((response) => {
  135. response.expires_at = (response.expires_in * 1000) + moment();
  136. response.refresh_token_expires_at = (response.refresh_token_lifetime * 1000) + moment();
  137.  
  138. const oauth = JSON.parse(JSON.stringify(this.$store.getters.get.oauth));
  139. this.set({ oauth: response, oauthUsurpator: oauth });
  140. }).then(redirect);
  141. },
  142. login(data, persistSession = true) {
  143. return this.oauth(this._.extend({
  144. grant_type: this.oauthGrantTypes.password,
  145. }, data), persistSession);
  146. },
  147. refresh() {
  148. if (this.pendingRefresh) {
  149. return new Promise((resolve) => {
  150. this.pendingRefresh.push(resolve);
  151. });
  152. } else {
  153. this.pendingRefresh = [];
  154. return this.oauth({
  155. grant_type: this.oauthGrantTypes.refreshToken,
  156. refresh_token: this.oauthStore.refresh_token,
  157. }).then(() => {
  158. this.pendingRefresh.forEach(Function.prototype.call, Function.prototype.call);
  159. this.pendingRefresh = false;
  160. });
  161. }
  162. },
  163. oauth(data, commit = true) {
  164. return this.request(this.build(this.oauthTokenEndpoint, this.http.post, this._.extend({
  165. client_id: this.oauthConfig.client_id,
  166. client_secret: this.oauthConfig.client_secret,
  167. }, data, { commit }))).then((response) => {
  168. response.expires_at = (response.expires_in * 1000) + moment();
  169. response.refresh_token_expires_at = (response.refresh_token_lifetime * 1000) + moment();
  170. if (commit) {
  171. this.set({ oauth: response });
  172. } else {
  173. // TODO handle rememberMe
  174. // this.$store._mutations.set[0](this.get(), data)
  175. }
  176. return response;
  177. });
  178. },
  179. request(config = {}) {
  180. const promise = this.wait ? this.syncRequest(config) : this.asyncRequest(config);
  181. this.wait = null;
  182. return promise;
  183. },
  184. async syncRequest(config) {
  185. const result = await this.asyncRequest(config);
  186. return result;
  187. },
  188. asyncRequest(config) {
  189. config.url = this.url(config);
  190. if (!config.headers) {
  191. config.headers = [];
  192. }
  193.  
  194. if (!this._.isEmpty(this.oauthStore) && config.url.indexOf(this.oauthTokenEndpoint) === -1) {
  195. if (this._.expired(this.oauthStore.expires_at)) {
  196. if (this._.expired(this.oauthStore.refresh_token_expires_at)) {
  197. this.unset('oauth');
  198. return this.redirect();
  199. }
  200. return this.refresh().then(this.asyncRequest.bind(this, config));
  201. }
  202.  
  203. config.headers = this._.extend({
  204. Authorization: `${this.oauthTokenTypes.bearer} ${this.oauthStore.access_token}`,
  205. }, config.headers);
  206. }
  207.  
  208. if (config.stringify) {
  209. config.data = QS.stringify(config.data);
  210. }
  211.  
  212. const multiPart = this._.some(config.data, this._.isBlob);
  213. if (multiPart) {
  214. config.data = this.encode(config.data);
  215. config.headers['X-Http-Method-Override'] = config.method;
  216. config.method = this.http.post;
  217. }
  218.  
  219. if (this._.isUndefined(config.cancelToken)) {
  220. config.cancelToken = this.cancelToken.token;
  221. }
  222.  
  223. return this.$http.request(config).then((res) => {
  224. let { data } = res;
  225. // eslint-disable-next-line no-underscore-dangle
  226. if (data._embedded && data._embedded.items) {
  227. // eslint-disable-next-line no-underscore-dangle
  228. data = data._embedded.items;
  229. }
  230. this.$store.data = data;
  231. this.$store[config.url] = data;
  232. return data;
  233. }).catch((error) => {
  234. const data = (error.response && error.response.data) || {};
  235. if (data.error === 'invalid_grant') {
  236. const description = data.error_description;
  237. if (description.match(/expired/i) && error.response.status === 401) {
  238. delete config.headers;
  239. return this.refresh().then(this.asyncRequest.bind(this, config));
  240. } else if (!description.match(/password/i) && description.match(/invalid|expired/i) && error.response.status >= 400) {
  241. this.unset('oauth');
  242. return this.redirect();
  243. }
  244. } else if (!this.$http.isCancel(error)) {
  245. // eslint-disable-next-line no-console
  246. console.error(error.response && error.response.data && error.response.data.error, {
  247. response: error.response,
  248. request: error.request,
  249. message: error.message,
  250. config: error.config,
  251. });
  252. }
  253. throw error;
  254. });
  255. },
  256. },
  257. });
  258.  
  259. Vue.set(Vue.prototype, '$ajax', Ajax);
  260.  
  261. export default Ajax;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement