visit
npm install yarn -g
mkdir simple-blog
cd simple-blog
vim package.json
{
"dependencies": {
"cosmicjs": "^2.39.0",
"express": "^4.15.2",
"hogan-express": "^0.5.2",
"nodemon": "^1.11.0"
},
"scripts": {
"start": "node app.js",
"development": "nodemon app.js"
}
}
yarn
vim app.js
const express = require('express')
const app = express()
const hogan = require('hogan-express')
const http_module = require('http')
const http = http_module.Server(app)
app.engine('html', hogan)
app.set('port', (process.env.PORT || 3000))
app.use('/', express.static(__dirname + '/public/'))
const Cosmic = require('cosmicjs')
const helpers = require('./helpers')
const bucket_slug = process.env.COSMIC_BUCKET || 'simple-blog-website'
const read_key = process.env.COSMIC_READ_KEY
const partials = {
header: 'partials/header',
footer: 'partials/footer'
}
app.use('/', (req, res, next) => {
res.locals.year = new Date().getFullYear()
next()
})
// Home
app.get('/', (req, res) => {
Cosmic.getObjects({ bucket: { slug: bucket_slug, read_key: read_key } }, (err, response) => {
const cosmic = response
if (cosmic.objects.type.posts) {
cosmic.objects.type.posts.forEach(post => {
const friendly_date = helpers.friendlyDate(new Date(post.created_at))
post.friendly_date = friendly_date.month + ' ' + friendly_date.date
})
} else {
cosmic.no_posts = true
}
res.locals.cosmic = cosmic
res.render('index.html', { partials })
})
})
http.listen(app.get('port'), () => {
console.info('==> 🌎 Go to //localhost:%s', app.get('port'));
})
mkdir views
cd views
vim index.html
{{> header }}
<main class="container">
{{# cosmic.objects.type.posts }}
<div class="card" data-href="/{{ slug }}">
{{# metadata.hero.imgix_url }}
<div class="blog-post-hero blog-post-hero--short" style="background-image: url({{ metadata.hero.imgix_url }})"></div>
{{/ metadata.hero.imgix_url }}
<div class="card-padding">
<h2 class="blog__title blog__title--small">
<a href="/{{ slug }}">{{ title }}</a>
</h2>
<div class="blog__author">
<div class="blog__author-image" style="background-image: url({{ metadata.author.metadata.image.imgix_url }}?w=100)"></div>
<div class="blog__author-title">by <a href="/author/{{ metadata.author.slug }}">{{ metadata.author.title }}</a> on {{ friendly_date }}</div>
<div class="clearfix"></div>
</div>
<div class="blog__teaser droid">{{{ metadata.teaser }}}</div>
<div class="blog__read-more">
<a href="/{{ slug }}">Read more...</a>
</div>
</div>
</div>
{{/ cosmic.objects.type.posts }}
</main>
{{> footer }}