NEXT craftinamerica.org. Base setup for headless wordpress https://www.craftinamerica.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

post.js 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import api from '../../utils/api'
  2. import { sortTypes } from '../../utils/helpers'
  3. const state = {
  4. all: [],
  5. loaded: false,
  6. singlePost: null,
  7. }
  8. const getters = {
  9. allPosts: state => state.all,
  10. allPostsLoaded: state => state.loaded,
  11. }
  12. const _arrangeByType = postsList => {
  13. const byType = {}
  14. postsList.forEach(post => {
  15. const subtypes = post.categories
  16. subtypes.forEach(type => {
  17. if (!byType[type]) byType[type] = []
  18. byType[type].push(post)
  19. })
  20. })
  21. const flatPacked = []
  22. Object.keys(byType).forEach(type => {
  23. flatPacked.push({ slug: type, title: type, inbetween: true })
  24. byType[type].forEach(post => flatPacked.push(post))
  25. })
  26. return flatPacked
  27. }
  28. const actions = {
  29. async getAllPosts({ commit }, { sortType, params }) {
  30. commit('CLEAR_POSTS')
  31. commit('POSTS_LOADED', false)
  32. const storeFetch = posts => {
  33. let repacked = posts
  34. if (sortType == sortTypes.subtype) {
  35. repacked = _arrangeByType(posts)
  36. }
  37. commit('STORE_FETCHED_POSTS', { posts: repacked })
  38. commit('POSTS_LOADED', true)
  39. }
  40. return await api.getByType({
  41. type: 'post',
  42. sort: sortType,
  43. params,
  44. cb: storeFetch,
  45. })
  46. },
  47. getMorePosts({ commit }, { sortType, params }) {
  48. const storeFetch = posts => {
  49. commit('ADD_TO_FETCHED_POSTS', { posts })
  50. commit('POSTS_LOADED', true)
  51. }
  52. return api.getByType({
  53. type: 'post',
  54. sort: sortType,
  55. params,
  56. cb: storeFetch,
  57. })
  58. },
  59. getSinglePost({ commit }, id) {
  60. commit('CLEAR_SINGLE_POSTS')
  61. commit('POSTS_LOADED', false)
  62. return api.getSingleType('post', id, post => {
  63. commit('STORE_FETCHED_SINGLE_POST', post)
  64. commit('POSTS_LOADED', true)
  65. })
  66. },
  67. }
  68. const mutations = {
  69. ADD_TO_FETCHED_POSTS(state, { posts }) {
  70. state.all = [...state.all, ...posts]
  71. },
  72. STORE_FETCHED_POSTS(state, { posts }) {
  73. state.all = posts
  74. },
  75. STORE_FETCHED_SINGLE_POST(state, post) {
  76. state.singlePost = post
  77. },
  78. CLEAR_POSTS(state) {
  79. state.all = []
  80. },
  81. CLEAR_SINGLE_POSTS(state) {
  82. state.singlePost = null
  83. },
  84. POSTS_LOADED(state, val) {
  85. state.loaded = val
  86. },
  87. }
  88. export default { state, getters, actions, mutations }