const keystone = require('keystone');
const Post = keystone.list('Post');
const PostCategory = keystone.list('PostCategory');

exports = module.exports = function (req, res) {
  const loadCategories = () => {
    return PostCategory.model.find().exec();
  };

  const loadPosts = () => {
    return Post.model.find().exec();
  };

  const returnObject = {
    posts: [],
    categories: [],
    success: false
  };

  const parseCategory = (category) => ({
    key: category.key,
    name: category.name,
    id: category.id
  });

  const parseCategories = (categories) => {
    return categories.map((cat) => parseCategory(cat))
  };

  const loadData = () => {
    const returnData = {
      posts: [],
      categories: [],
      error: null
    };
    loadPosts().then((posts) => {
      console.log("Calling load posts with: ", posts)
      loadedPosts = posts;
      return loadCategories()
    }).then((categories) => {
      console.log("Calling load categories with: ", categories)
      return res.apiResponse({ success: true, posts: loadedPosts, categories: parseCategories(categories) })
    }).catch((error) => {
      console.log("Calling error with: ", error)
      return res.state(500).send({ error: `An error occured: ${error.message}` });
    });
  }

  loadData();
};

@@ -328,93 +328,8 @@
 %7D;%0A%0A
-  const returnObject = %7B%0A    posts: %5B%5D,%0A    categories: %5B%5D,%0A    success: false%0A  %7D;%0A%0A
   co
@@ -580,180 +580,63 @@
     
-const returnData = %7B%0A      posts: %5B%5D,%0A      categories: %5B%5D,%0A      error: null%0A    %7D;%0A    loadPosts().then((posts) =%3E %7B%0A      console.log(%22Calling load posts with: %22, posts)
+let loadedPosts = %5B%5D;%0A    loadPosts().then((posts) =%3E %7B
 %0A   
@@ -723,72 +723,8 @@
 %3E %7B%0A
-      console.log(%22Calling load categories with: %22, categories)%0A
     
@@ -749,16 +749,24 @@
 sponse(%7B
+%0A       
  success
@@ -772,16 +772,24 @@
 s: true,
+%0A       
  posts: 
@@ -800,16 +800,24 @@
 edPosts,
+%0A       
  categor
@@ -848,19 +848,26 @@
 egories)
+%0A     
  %7D)
+;
 %0A    %7D).
@@ -933,16 +933,17 @@
 , error)
+;
 %0A      r

remove boilerplate and unneeded functions from getAll