orderiom-api-package 0.4.91 → 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.91",
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,32 +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 axios.post(`api/basket/unassigned-basket`, {
159
- basketId: basketsIdToUnassign
160
- })
161
- .then(res => res)
162
- .catch(commonErrorCallback());
163
- }
164
-
165
- const getAuthToken = async (hadPrivateToken = false) => {
140
+ const getAuthToken = async ($store, hadPrivateToken = false) => {
166
141
  isFetchingToken = true;
167
142
  try {
168
143
  const getTokenRes = await axios.post(getTokenAPI, {
@@ -172,7 +147,10 @@ const getAuthToken = async (hadPrivateToken = false) => {
172
147
  })
173
148
  window.localStorage.setItem("publicToken", getTokenRes.data.data.access_token);
174
149
 
175
- if(hadPrivateToken) await unassignBasket();
150
+ if(hadPrivateToken) {
151
+ $store.commit("auth/clearAuthData");
152
+ await $store.dispatch('unassignBasket');
153
+ }
176
154
  } catch (error) {
177
155
  return commonErrorCallback()(error)
178
156
  } finally {
@@ -184,95 +162,98 @@ const getAuthToken = async (hadPrivateToken = false) => {
184
162
  }
185
163
 
186
164
  axios.defaults.baseURL = process.env.VUE_APP_BASE_API_URL || window.dynamicData.VUE_APP_BASE_API_URL;
187
- axios.interceptors.request.use(config => {
188
- // exception API that does not need any pre-process
189
- if(config.url === getTokenAPI) return config;
190
-
191
- // attach restaurant ID to all other requests
192
- const key = config.method === 'get' ? 'params' : 'data';
193
- const data = config[key] || {};
194
- const idFromEnv = restaurantIdEnv();
195
- if(idFromEnv && !data.restaurantId) data.restaurantId = idFromEnv;
196
- config[key] = data;
197
-
198
- // use the valid token if possible
199
- let token = localStorage.getItem("privateToken") || localStorage.getItem("publicToken");
200
- if(token && !isTokenExpired(token)){
201
- config.headers["Authorization"] = `Bearer ${token}`
202
- return config;
203
- }
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
+ }
204
183
 
205
- // if the token is expired or does not exist, wait for public token to be fetched
206
- return new Promise((resolve, reject) => {
207
- const hadPrivateToken = !!localStorage.getItem("privateToken");
208
- // remove invalid or expired tokens
209
- token = null;
210
- localStorage.removeItem("privateToken");
211
- 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
+ });
212
210
 
213
- // Push the request to waitlist and wait for new token to be fetched
214
- reqBuffer.push(() => {
215
- const newToken = localStorage.getItem("publicToken");
216
- if(newToken){
217
- config.headers["Authorization"] = `Bearer ${newToken}`
218
- resolve(config);
219
- } else {
220
- config.headers["Authorization"] = undefined;
221
- 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
+ }
222
241
  }
223
- });
224
-
225
- // Start to fetch token if it is not already fetching
226
- if(!isFetchingToken) getAuthToken(hadPrivateToken);
227
- })
228
- }, error => {
229
- return Promise.reject(error);
230
- });
231
- axios.interceptors.response.use(
232
- res => {
233
- return {
234
- type: 'success',
235
- msg: '',
236
- status: res.status,
237
- data: res.data
238
- }
239
- },
240
- error => {
241
- if (
242
- error.response &&
243
- error.response.data &&
244
- error.response.data.error &&
245
- error.response.data.error.validation
246
- ) {
247
- const validation = error.response.data.error.validation;
248
242
 
249
243
  if (
250
- (
251
- Object.keys(validation).includes("basketId") &&
252
- validation["basketId"][0] === "basket_does_not_exists"
253
- ) ||
254
- (
255
- Object.keys(validation).includes("restaurantId") &&
256
- validation["restaurantId"][0] === "basket_does_not_exists"
257
- )
244
+ error.response &&
245
+ error.response.status === 422 &&
246
+ error.response.data &&
247
+ error.response.data.message &&
248
+ error.response.data.message.body === "unauthenticated"
258
249
  ) {
259
- localStorage.removeItem("basket");
250
+ localStorage.clear();
251
+ window.location.reload();
260
252
  }
261
- }
262
253
 
263
- if (
264
- error.response &&
265
- error.response.status === 422 &&
266
- error.response.data &&
267
- error.response.data.message &&
268
- error.response.data.message.body === "unauthenticated"
269
- ) {
270
- localStorage.clear();
271
- window.location.reload();
254
+ return Promise.reject(error);
272
255
  }
273
-
274
- return Promise.reject(error);
275
- }
276
- );
256
+ );
257
+ }
277
258
 
278
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