-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
61 lines (54 loc) · 1.75 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*!
* koa-better-serve <https://github.com/tunnckoCore/koa-better-serve>
*
* Copyright (c) 2017 Charlike Mike Reagent <open.source.charlike@gmail.com> (https://i.am.charlike.online)
* Released under the MIT license.
*/
import send from 'koa-send'
import kindOf from 'kind-of'
/**
* Serving `dir` of files and folders, when request
* url (`ctx.url`) match to `pathname`. All behind
* the scenes is just using [koa-send][].
* **Hint:** use [koa-convert][] to use it for [koa][] v1.
*
* @example
* const serve = require('koa-better-serve')
* const Koa = require('koa')
* const app = new Koa()
*
* app.use(serve('./uploads/images', '/images'))
* app.listen(4290)
*
* @param {String|Buffer} root folder to serve
* @param {String|RegExp} pathname path to match, can be regex
* @param {Object} options optional, passed directly to [koa-send][]
* @return {Function} a [koa][] plugin which returns `Promise` when called
* @name koaBetterServe
* @public
*/
export default function koaBetterServe (root, pathname, options) {
if (kindOf(root) !== 'string') {
throw new TypeError('koa-better-serve: expect `root` to be string')
}
if (kindOf(pathname) === 'object') {
options = pathname
pathname = '/'
}
options = kindOf(options) === 'object' ? options : null
options = Object.assign({ root }, options)
pathname = pathname || '/'
if (kindOf(pathname) !== 'string') {
throw new TypeError('koa-better-serve: expect `pathname` to be string')
}
return (ctx, next) => {
const filepath = ctx.path.replace(pathname, '')
return send(ctx, filepath, options).catch((er) => {
/* istanbul ignore else */
if (er.code === 'ENOENT' && er.status === 404) {
ctx.status = 404
ctx.body = 'Not Found'
}
})
}
}