-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
107 lines (91 loc) · 2.04 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*!
* qn-cnpm - index.js
*
* Copyright(c) cnpmjs.org and other contributors.
* MIT Licensed
*
* Authors:
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
* dead_horse <dead_horse@qq.com> (https://github.com/dead-horse)
*/
'use strict';
/**
* Module dependencies.
*/
var thunkify = require('thunkify-wrap');
var qn = require('qn');
var fs = require('fs');
/**
* Expose `Client`
*/
module.exports = Client;
/**
* qn cnpm wrapper
* @param {Object} options for qn client
*/
function Client(options) {
if (!(this instanceof Client)) {
return new Client(options);
}
this.client = qn.create(options);
thunkify(this.client, ['delete', 'uploadFile', 'upload', 'download']);
}
/**
* Upload file
*
* @param {String} filepath
* @param {Object} options
* - {String} key
* - {Number} size
*/
Client.prototype.upload = function* (filepath, options) {
try {
yield this.client.delete(options.key);
} catch (err) {
// ignore error here
}
var res = yield this.client.uploadFile(filepath, {
key: options.key,
size: options.size
});
return { url: parseUrl(res) };
};
Client.prototype.uploadBuffer = function* (buf, options) {
try {
yield this.client.delete(options.key);
} catch (err) {
// ignore error here
}
var res = yield this.client.upload(buf, {key: options.key});
return { url: parseUrl(res) };
};
function parseUrl(res) {
if (!res || !res[0] || !res[0].url) {
return null;
}
var url = res[0].url;
if (url.indexOf('http') !== 0) {
url = 'http://' + url;
}
return url;
}
Client.prototype.url = function (key) {
return this.client.resourceURL(key);
};
Client.prototype.download = function* (key, filepath, options) {
var writeStream = fs.createWriteStream(filepath);
yield this.client.download(key, {
timeout: options.timeout,
writeStream: writeStream
});
};
Client.prototype.remove = function* (key) {
try {
return yield this.client.delete(key);
} catch (err) {
if (err.name === 'QiniuFileNotExistsError') {
return;
}
throw err;
}
};