import models from '../models/index';
import React from 'react';
import { renderToString } from 'react-dom/server';
import Articles from '../assets/javascripts/components/articles.jsx';
import { markdown } from '../helpers/markdown';
import fs from 'fs';

const index = async (ctx, _next) => {
  let page = parseInt(ctx.query.page, 10) || 1;
  page = page > 0 ? page : 1;
  let pageOffset = ( page - 1 ) * 10;
  const articleCount = await models.Article.count();
  const articles = await models.Article.findAll({
    include: [{
      model: models.User,
      attributes: ['id', 'name']
    }],
    attributes: ['id', 'title', 'description', 'created_at'],
    order: 'created_at DESC',
    offset: pageOffset,
    limit: 10
  });
  const prerenderHtml = await renderToString(
    <Articles articles={ articles } />
  );
  // ctx.session.userId = 4
  const locals = {
    title: 'Home',
    nav: 'index',
    prerenderHtml: prerenderHtml,
    preloadedState: { articles: articles },
    baseUrl: '/',
    currentPage: page,
    pages: parseInt(articleCount / 10 + 1)
  };
  await ctx.render('home/index', locals);
};

const about = async (ctx, _next) => {
  const readme = fs.readFileSync('README.md', 'utf8');
  const locals = {
    title: 'About',
    nav: 'about',
    content: readme,
    markdown: markdown
  };
  await ctx.render('home/about', locals);
};

export default {
  index,
  about
};

@@ -422,94 +422,18 @@
 icle
-Count = await models.Article.count();%0A  const articles = await models.Article.findAll(
+s_query = 
 %7B%0A  
@@ -646,16 +646,147 @@
 : 10%0A  %7D
+;%0A  const %5BarticleCount, articles%5D = await Promise.all(%5B%0A    models.Article.count(),%0A    models.Article.findAll(articles_query)%0A  %5D
 );%0A  con
@@ -874,36 +874,8 @@
  );%0A
-  // ctx.session.userId = 4%0A
   co
@@ -1177,16 +1177,16 @@
 t) =%3E %7B%0A
-
   const 
@@ -1193,16 +1193,22 @@
 readme =
+ await
  fs.read

use promise all