Crowi.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * Crowi context class for client
  3. */
  4. import axios from 'axios'
  5. export default class Crowi {
  6. constructor(context, window) {
  7. this.context = context;
  8. this.location = window.location || {};
  9. this.document = window.document || {};
  10. this.apiGet = this.apiGet.bind(this);
  11. this.apiPost = this.apiPost.bind(this);
  12. this.apiRequest = this.apiRequest.bind(this);
  13. }
  14. apiGet(path, params) {
  15. return this.apiRequest('get', path, params);
  16. }
  17. apiPost(path, params) {
  18. return this.apiRequest('post', path, params);
  19. }
  20. apiRequest(method, path, params) {
  21. return new Promise((resolve, reject) => {
  22. axios[method](`/_api${path}`, {params})
  23. .then(res => {
  24. if (res.data.ok) {
  25. resolve(res.data);
  26. } else {
  27. // FIXME?
  28. throw new Error(res.data);
  29. }
  30. }).catch(res => {
  31. // FIXME?
  32. throw new Error(res);
  33. });
  34. });
  35. }
  36. static escape (html, encode) {
  37. return html
  38. .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
  39. .replace(/</g, '&lt;')
  40. .replace(/>/g, '&gt;')
  41. .replace(/"/g, '&quot;')
  42. .replace(/'/g, '&#39;');
  43. }
  44. static unescape(html) {
  45. return html.replace(/&([#\w]+);/g, function(_, n) {
  46. n = n.toLowerCase();
  47. if (n === 'colon') return ':';
  48. if (n.charAt(0) === '#') {
  49. return n.charAt(1) === 'x'
  50. ? String.fromCharCode(parseInt(n.substring(2), 16))
  51. : String.fromCharCode(+n.substring(1));
  52. }
  53. return '';
  54. });
  55. }
  56. }