UNPKG

3.03 kBtext/coffeescriptView Raw
1fs = require 'fs'
2helpers = require './helpers'
3eco = require 'eco'
4
5PostSchema = new app.mongoose.Schema
6 title: String
7 topic: String
8 body: String
9 slug: String
10 date: Date
11
12PostSchema.method 'uri', (text) ->
13 "#{app.conf.website_url}/posts/#{@slug}"
14
15PostSchema.method 'update', (text) ->
16 lines = text.split('\n')
17 @title = lines.first()
18 @topic = lines[1]
19 @date = lines.last().toDate()
20 @body = lines.slice(2, lines.length - 1).join('\n')
21 this.save()
22
23
24PostSchema.static 'update_or_create', (file, callback) ->
25 slug = file.name.split('.')[0]
26 text = fs.readFileSync file.path, 'utf-8'
27
28 Post.findOne {slug: slug}, (err, post) ->
29 unless post
30 post = new Post
31 post.slug = slug
32
33 post.update(text)
34 callback()
35
36PostSchema.static 'topics', (callback) ->
37 Post.find {}, (err, posts) ->
38 topics = []
39 Object.each posts.groupBy('topic'), (topic, list) ->
40 topics.push
41 name: topic
42 posts: list.sortBy('date', desc=true)
43
44 topics = topics.sortBy ((t) -> t.posts.first().date), desc=true
45 callback(topics)
46
47
48Post = app.mongoose.model('Post', PostSchema)
49
50module.exports = Post
51
52
53app.post '/posts', (req, res) ->
54 req.form.complete (err, fields, files) ->
55 if err
56 next(err)
57 else
58 file = files.file
59 Post.update_or_create file, ->
60 res.send 'ok\n'
61
62
63app.delete '/posts/:slug', (req, res) ->
64 Post.findOne {slug: req.params.slug}, (err, post) ->
65 if post
66 post.remove ->
67 res.send "ok\n"
68 else
69 res.send "not found\n"
70
71
72app.get '/', (req, res) ->
73 Post.topics (topics) ->
74 req.topics = topics
75 res.render 'home/main', req
76
77
78app.get '/posts/:slug', (req, res, next) ->
79 Post.findOne {slug: req.params.slug}, (err, post) ->
80 if post?
81 req.title = post.title
82 post.body = helpers.html(post.body)
83 req.post = post
84 res.render 'post/main', req
85 else
86 next()
87
88
89app.get '/api/posts', (req, res) ->
90 Post.topics (topics) ->
91 res.contentType 'application/json'
92 res.send topics
93
94
95app.get '/api/posts/:slug', (req, res, next) ->
96 Post.findOne {slug: req.params.slug}, (err, post) ->
97 if post?
98 post.body = helpers.html(post.body)
99 res.send post
100 else
101 next()
102
103app.get '/sitemap.xml', (req, res, next) ->
104 Post.find {}, (err, posts) ->
105 res.send eco.render """<?xml version="1.0" encoding="UTF-8" ?>
106 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
107 xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0">
108 <!-- http://www.google.com/support/webmasters/bin/answer.py?answer=34648 -->
109 <url><loc><%= @conf.website_url %></loc><mobile:mobile/></url>
110 <% for p in @posts: %>
111 <url><loc><%= p.uri() %></loc><mobile:mobile/></url><% end %>
112 </urlset>""", { posts: posts, conf: app.conf }
113