orderiom-api-package 0.4.92 → 0.4.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts CHANGED
@@ -6,6 +6,7 @@ export const $http: Object;
6
6
  export const weekdays: string[];
7
7
  export const formatDate: (date: Date) => string;
8
8
  export const formatTime: (date: Date) => string;
9
+ export const defineInterceptors: (params: Record<string, any>) => void;
9
10
 
10
11
  export interface AuthState<SignedIn extends boolean> {
11
12
  privateToken: string | null,
package/index.js CHANGED
@@ -2,7 +2,7 @@ import apiStore from './src';
2
2
  import enMsg from "./src/messages/en-api.json";
3
3
  import deMsg from "./src/messages/de-api.json";
4
4
  import frMsg from './src/messages/fr-api.json';
5
- import {$http as api, weekdays, formatDate, formatTime} from './src/common';
5
+ import {$http as api, defineInterceptors as di, weekdays, formatDate, formatTime} from './src/common';
6
6
 
7
7
  function install(Vue, options = {}, config = {}) {
8
8
  if (!options.store) console.log('Please provide a store!!');
@@ -10,6 +10,7 @@ function install(Vue, options = {}, config = {}) {
10
10
  }
11
11
 
12
12
  export const $http = api;
13
+ export const defineInterceptors = di;
13
14
  export default {
14
15
  install,
15
16
  enMsg,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "orderiom-api-package",
3
- "version": "0.4.92",
3
+ "version": "0.4.93",
4
4
  "description": "This package will install all necessary API calls for every orderiom restaurant",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
package/src/common.js CHANGED
@@ -137,34 +137,7 @@ let isFetchingToken = false;
137
137
  const reqBuffer = []; // List of axios requests waiting for the fetch of public token (Each item is a function)
138
138
  const getTokenAPI = "api/oauth/token"; // API to get public token needs
139
139
 
140
- export const unassignBasket = (restaurantId = null) => {
141
- restaurantId = restaurantId || restaurantIdEnv();
142
- let baskets = JSON.parse(localStorage.getItem("basket"));
143
-
144
- if(!Array.isArray(baskets) || !baskets.length) return;
145
-
146
- // Find all basketId where restaurantId does not exist, or find all basketId linked to a specific restaurantId if it exists.
147
- const basketsIdToUnassign = baskets.filter(basket => (
148
- basket.basketId &&
149
- (
150
- !Number(restaurantId) ||
151
- (
152
- Number(restaurantId) === Number(basket.restaurantId)
153
- )
154
- )
155
- )).map(basket => basket.basketId)
156
-
157
- // unassign all filtered baskets from logged-in user (so these baskets would not need a private token anymore)
158
- return Promise.all(
159
- basketsIdToUnassign.map(basketId =>
160
- axios.post(`api/basket/unassigned-basket`, {
161
- basketId
162
- })
163
- )
164
- ).catch(commonErrorCallback())
165
- }
166
-
167
- const getAuthToken = async (hadPrivateToken = false) => {
140
+ const getAuthToken = async ($store, hadPrivateToken = false) => {
168
141
  isFetchingToken = true;
169
142
  try {
170
143
  const getTokenRes = await axios.post(getTokenAPI, {
@@ -174,7 +147,10 @@ const getAuthToken = async (hadPrivateToken = false) => {
174
147
  })
175
148
  window.localStorage.setItem("publicToken", getTokenRes.data.data.access_token);
176
149
 
177
- if(hadPrivateToken) await unassignBasket();
150
+ if(hadPrivateToken) {
151
+ $store.commit("auth/clearAuthData");
152
+ await $store.dispatch('unassignBasket');
153
+ }
178
154
  } catch (error) {
179
155
  return commonErrorCallback()(error)
180
156
  } finally {
@@ -186,95 +162,98 @@ const getAuthToken = async (hadPrivateToken = false) => {
186
162
  }
187
163
 
188
164
  axios.defaults.baseURL = process.env.VUE_APP_BASE_API_URL || window.dynamicData.VUE_APP_BASE_API_URL;
189
- axios.interceptors.request.use(config => {
190
- // exception API that does not need any pre-process
191
- if(config.url === getTokenAPI) return config;
192
-
193
- // attach restaurant ID to all other requests
194
- const key = config.method === 'get' ? 'params' : 'data';
195
- const data = config[key] || {};
196
- const idFromEnv = restaurantIdEnv();
197
- if(idFromEnv && !data.restaurantId) data.restaurantId = idFromEnv;
198
- config[key] = data;
199
-
200
- // use the valid token if possible
201
- let token = localStorage.getItem("privateToken") || localStorage.getItem("publicToken");
202
- if(token && !isTokenExpired(token)){
203
- config.headers["Authorization"] = `Bearer ${token}`
204
- return config;
205
- }
165
+ export const defineInterceptors = ({$store}) => {
166
+ axios.interceptors.request.use(config => {
167
+ // exception API that does not need any pre-process
168
+ if(config.url === getTokenAPI) return config;
169
+
170
+ // attach restaurant ID to all other requests
171
+ const key = config.method === 'get' ? 'params' : 'data';
172
+ const data = config[key] || {};
173
+ const idFromEnv = restaurantIdEnv();
174
+ if(idFromEnv && !data.restaurantId) data.restaurantId = idFromEnv;
175
+ config[key] = data;
176
+
177
+ // use the valid token if possible
178
+ let token = localStorage.getItem("privateToken") || localStorage.getItem("publicToken");
179
+ if(token && !isTokenExpired(token)){
180
+ config.headers["Authorization"] = `Bearer ${token}`
181
+ return config;
182
+ }
206
183
 
207
- // if the token is expired or does not exist, wait for public token to be fetched
208
- return new Promise((resolve, reject) => {
209
- const hadPrivateToken = !!localStorage.getItem("privateToken");
210
- // remove invalid or expired tokens
211
- token = null;
212
- localStorage.removeItem("privateToken");
213
- localStorage.removeItem("publicToken");
184
+ // if the token is expired or does not exist, wait for public token to be fetched
185
+ return new Promise((resolve, reject) => {
186
+ const hadPrivateToken = !!localStorage.getItem("privateToken");
187
+ // remove invalid or expired tokens
188
+ token = null;
189
+ localStorage.removeItem("privateToken");
190
+ localStorage.removeItem("publicToken");
191
+
192
+ // Push the request to waitlist and wait for new token to be fetched
193
+ reqBuffer.push(() => {
194
+ const newToken = localStorage.getItem("publicToken");
195
+ if(newToken){
196
+ config.headers["Authorization"] = `Bearer ${newToken}`
197
+ resolve(config);
198
+ } else {
199
+ config.headers["Authorization"] = undefined;
200
+ reject(`Not authorized! token required for ${config.url}.`);
201
+ }
202
+ });
203
+
204
+ // Start to fetch token if it is not already fetching
205
+ if(!isFetchingToken) getAuthToken($store, hadPrivateToken);
206
+ })
207
+ }, error => {
208
+ return Promise.reject(error);
209
+ });
214
210
 
215
- // Push the request to waitlist and wait for new token to be fetched
216
- reqBuffer.push(() => {
217
- const newToken = localStorage.getItem("publicToken");
218
- if(newToken){
219
- config.headers["Authorization"] = `Bearer ${newToken}`
220
- resolve(config);
221
- } else {
222
- config.headers["Authorization"] = undefined;
223
- reject(`Not authorized! token required for ${config.url}.`);
211
+ axios.interceptors.response.use(
212
+ res => {
213
+ return {
214
+ type: 'success',
215
+ msg: '',
216
+ status: res.status,
217
+ data: res.data
218
+ }
219
+ },
220
+ error => {
221
+ if (
222
+ error.response &&
223
+ error.response.data &&
224
+ error.response.data.error &&
225
+ error.response.data.error.validation
226
+ ) {
227
+ const validation = error.response.data.error.validation;
228
+
229
+ if (
230
+ (
231
+ Object.keys(validation).includes("basketId") &&
232
+ validation["basketId"][0] === "basket_does_not_exists"
233
+ ) ||
234
+ (
235
+ Object.keys(validation).includes("restaurantId") &&
236
+ validation["restaurantId"][0] === "basket_does_not_exists"
237
+ )
238
+ ) {
239
+ localStorage.removeItem("basket");
240
+ }
224
241
  }
225
- });
226
-
227
- // Start to fetch token if it is not already fetching
228
- if(!isFetchingToken) getAuthToken(hadPrivateToken);
229
- })
230
- }, error => {
231
- return Promise.reject(error);
232
- });
233
- axios.interceptors.response.use(
234
- res => {
235
- return {
236
- type: 'success',
237
- msg: '',
238
- status: res.status,
239
- data: res.data
240
- }
241
- },
242
- error => {
243
- if (
244
- error.response &&
245
- error.response.data &&
246
- error.response.data.error &&
247
- error.response.data.error.validation
248
- ) {
249
- const validation = error.response.data.error.validation;
250
242
 
251
243
  if (
252
- (
253
- Object.keys(validation).includes("basketId") &&
254
- validation["basketId"][0] === "basket_does_not_exists"
255
- ) ||
256
- (
257
- Object.keys(validation).includes("restaurantId") &&
258
- validation["restaurantId"][0] === "basket_does_not_exists"
259
- )
244
+ error.response &&
245
+ error.response.status === 422 &&
246
+ error.response.data &&
247
+ error.response.data.message &&
248
+ error.response.data.message.body === "unauthenticated"
260
249
  ) {
261
- localStorage.removeItem("basket");
250
+ localStorage.clear();
251
+ window.location.reload();
262
252
  }
263
- }
264
253
 
265
- if (
266
- error.response &&
267
- error.response.status === 422 &&
268
- error.response.data &&
269
- error.response.data.message &&
270
- error.response.data.message.body === "unauthenticated"
271
- ) {
272
- localStorage.clear();
273
- window.location.reload();
254
+ return Promise.reject(error);
274
255
  }
275
-
276
- return Promise.reject(error);
277
- }
278
- );
256
+ );
257
+ }
279
258
 
280
259
  export const $http = axios;
@@ -189,7 +189,30 @@ const actions = {
189
189
  );
190
190
  },
191
191
  unassignBasket(_, restaurantId) {
192
- return unassignBasket(restaurantId);
192
+ restaurantId = restaurantId || restaurantIdEnv();
193
+ let baskets = JSON.parse(localStorage.getItem("basket"));
194
+
195
+ if(!Array.isArray(baskets) || !baskets.length) return;
196
+
197
+ // Find all basketId where restaurantId does not exist, or find all basketId linked to a specific restaurantId if it exists.
198
+ const basketsIdToUnassign = baskets.filter(basket => (
199
+ basket.basketId &&
200
+ (
201
+ !Number(restaurantId) ||
202
+ (
203
+ Number(restaurantId) === Number(basket.restaurantId)
204
+ )
205
+ )
206
+ )).map(basket => basket.basketId)
207
+
208
+ // unassign all filtered baskets from logged-in user (so these baskets would not need a private token anymore)
209
+ return Promise.all(
210
+ basketsIdToUnassign.map(basketId =>
211
+ $http.post(`api/basket/unassigned-basket`, {
212
+ basketId
213
+ })
214
+ )
215
+ ).catch(commonErrorCallback())
193
216
  },
194
217
  restaurantInfo({ commit }, restaurantId) {
195
218
  return $http