UNPKG

1.57 kBJavaScriptView Raw
1var extend = require('util')._extend;
2var Fs = require('fs');
3var Path = require('path');
4var Styledown = require('./index');
5
6/**
7 * Defaults
8 */
9
10var defaults = {
11 path: '/styleguides',
12 root: process.cwd(),
13 sources: {}
14};
15
16
17/**
18 * Middleware
19 */
20
21function Middleware (options) {
22 this.options = {};
23 extend(this.options, defaults);
24 extend(this.options, options);
25}
26
27Middleware.prototype = {
28
29 /**
30 * Handler
31 */
32
33 run: function (req, res, next) {
34 var options = this.options;
35
36 // No need unless it matches `path`
37 if (req.path.substr(0, options.path.length) !== options.path)
38 return;
39
40 var path = req.path.substr(options.path.length + 1);
41 req.subpath = path;
42
43 if (path === 'styledown.css') {
44 res.set('Content-Type', 'text/css');
45 res.send(200, "body { color: #333; }");
46 return;
47 }
48
49 if (path === 'styledown.js') {
50 res.set('Content-Type', 'application/javascript');
51 res.send(200, "alert('hi');");
52 return;
53 }
54
55 if (options.guides[path]) {
56 var file = Path.join(options.root, options.guides[path]);
57
58 Fs.exists(file, function (exists) {
59 if (!exists) next();
60
61 Fs.readFile(file, function (err, data) {
62 var src = data.toString();
63 var html = Styledown.parseSync(src);
64 res.send(200, html);
65 });
66 });
67 return;
68 }
69
70 next();
71 }
72};
73
74/**
75 * Exports
76 */
77
78module.exports = function (options) {
79 var m = new Middleware(options);
80
81 return function (req, res, next) {
82 return m.run(req, res, next);
83 };
84};