Advertisement
Guest User

Untitled

a guest
Jul 27th, 2016
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. import fetch from 'node-fetch';
  2.  
  3. const MESSAGES_TO_SEND = 20;
  4. const CHANNEL_ID = 'bd89eb93-9d5c-49d7-bb18-7f1d750247e8'; // #Kanal 2
  5. const USER = { username: 'admin', password: 'Sommer2016!' };
  6. const URL = 'http://192.168.0.50/Feed';
  7.  
  8. let accessToken = '';
  9.  
  10.  
  11. const handleError = res => {
  12. if (res.status >= 200 && res.status < 300) {
  13. return res;
  14. } else {
  15. const error = new Error(res.statusText);
  16. error.response = res;
  17. throw error;
  18. }
  19. };
  20.  
  21. const parseJson = res => {
  22. switch (res.status) {
  23. case 204:
  24. return [];
  25. default:
  26. return res.json();
  27. }
  28. };
  29.  
  30. fetch(`${URL}/users/login`, {
  31. method: 'post',
  32. headers: {
  33. 'Authorization': '',
  34. 'Content-Type': 'application/json'
  35. },
  36. body: JSON.stringify(USER)
  37. })
  38. .then(handleError)
  39. .then(parseJson)
  40. .then(res => accessToken = res.accessToken)
  41. .then(() => {
  42. const messagePromises = [];
  43. for (let i = 1; i < MESSAGES_TO_SEND+1; i++) {
  44. console.log(`Melding ${i} sendt.`); // eslint-disable-line no-console
  45. messagePromises.push(
  46. fetch(`${URL}/channels/${CHANNEL_ID}/entries`, {
  47. method: 'post',
  48. headers: {
  49. 'Authorization': `Bearer ${accessToken}`,
  50. 'Content-Type': 'application/json'
  51. },
  52. body: JSON.stringify({message: `Testmelding ${i}`})
  53. }).then(
  54. res => console.log(`Melding ${i}: ${res.status}`) // eslint-disable-line no-console
  55. )
  56. );
  57. }
  58.  
  59. Promise.all(messagePromises).then(
  60. () => console.log('Ferdig!') // eslint-disable-line no-console
  61. );
  62.  
  63. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement