fetch.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License.
  4. */
  5. var axios = require('axios');
  6. /**
  7. * Attaches a given access token to a MS Graph API call
  8. * @param endpoint: REST API endpoint to call
  9. * @param accessToken: raw access token string
  10. */
  11. async function fetch(endpoint, accessToken, param) {
  12. const options = {
  13. headers: {
  14. Authorization: `Bearer ${accessToken}`
  15. }
  16. };
  17. if (!param) {
  18. param = {};
  19. }
  20. console.log(`request made to ${endpoint} at: ` + new Date().toString());
  21. try {
  22. const response = await axios.get(endpoint, options, param);
  23. return await response.data;
  24. } catch (error) {
  25. throw new Error(error);
  26. }
  27. }
  28. async function updateFetch(endpoint, accessToken, params) {
  29. const options = {
  30. headers: {
  31. Authorization: `Bearer ${accessToken}`
  32. }
  33. };
  34. console.log(`request made to ${endpoint} at: ` + new Date().toString());
  35. if (!params) {
  36. params = {};
  37. }
  38. else {
  39. params = JSON.parse(params);
  40. }
  41. try {
  42. const response = await axios.post(endpoint, params, options);
  43. return await response.data;
  44. } catch (error) {
  45. throw new Error(error);
  46. }
  47. }
  48. module.exports = {
  49. fetch : (endpoint, accessToken)=> fetch(endpoint, accessToken),
  50. updateFetch: (endpoint, accessToken, params)=> updateFetch(endpoint, accessToken, params),
  51. }