Guest User

Untitled

a guest
Oct 21st, 2019
120
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Realm from "../../configs/realm";
  2.  
  3. /**
  4. * nameSchema Bookmark
  5. * id: { type: 'int' },
  6. * title: { type: 'string' },
  7. * content: { type: 'string' },
  8. * hide: { type: 'bool' },
  9. * tags: { type: 'data', objectType: 'Tag' },
  10. * timeCreate: { type: 'string' },
  11. * timeUpdate: { type: 'string' },
  12. */
  13.  
  14. import Tag from "./tag";
  15.  
  16. const get = () => {
  17. return Realm.objects("Bookmark");
  18. };
  19.  
  20. const add = ({
  21. title = "",
  22. content,
  23. hide = false,
  24. tags = [],
  25. timeCreate = new Date().toString(),
  26. timeUpdate = new Date().toString()
  27. }) => {
  28. try {
  29. if (!content) throw "Error : content is requi";
  30. else
  31. Realm.write(() => {
  32. //create fied id
  33. let arr = get().sorted("id");
  34. let id = arr.length !== 0 ? arr[arr.length - 1]["id"] + 1 : 1;
  35. //create Bookmark
  36. Realm.create("Bookmark", {
  37. id: id,
  38. title,
  39. content,
  40. hide,
  41. tags,
  42. timeCreate,
  43. timeUpdate
  44. });
  45. });
  46. } catch (e) {
  47. console.log(e);
  48. }
  49. };
  50.  
  51. const addAll = arr =>
  52. new Promise((resolve, reject) => {
  53. try {
  54. arr.forEach(element => {
  55. add({
  56. title: element.title,
  57. content: element.content,
  58. hide: element.hide,
  59. tags: element.tags,
  60. timeCreate: element.timeCreate,
  61. timeUpdate: element.timeUpdate
  62. });
  63. });
  64. resolve(arr);
  65. } catch (e) {
  66. reject(e);
  67. console.log(e);
  68. }
  69. });
  70.  
  71. const edit = (resuft, { title, content, hide, tags }) => {
  72. try {
  73. Realm.write(() => {
  74. resuft.title = title || resuft.title;
  75. resuft.content = content || resuft.content;
  76. resuft.hide = hide || resuft.hide;
  77. resuft.timeUpdate = new Date().toString();
  78. if (tags) {
  79. resuft.tags.forEach(v => {
  80. resuft.tags.pop();
  81. });
  82. tags.forEach(tag => {
  83. resuft.tags.push(tag);
  84. });
  85. }
  86. });
  87. } catch (error) {
  88. console.log(e);
  89. }
  90. };
  91.  
  92. const remove = index => {
  93. try {
  94. Realm.write(() => {
  95. Realm.delete(get().filtered(`id = ${index}`));
  96. });
  97. } catch (e) {
  98. console.log("remove", e);
  99. }
  100. };
  101.  
  102. const removeAll = () => {
  103. try {
  104. Realm.write(() => {
  105. Realm.delete(get());
  106. });
  107. } catch (e) {
  108. console.log("error", e);
  109. }
  110. };
  111.  
  112. export default {
  113. get,
  114. add,
  115. addAll,
  116. edit,
  117. remove,
  118. removeAll
  119. };
RAW Paste Data