Last active
April 28, 2017 09:32
-
-
Save Chunlin-Li/415df6707329ab1fe24532e13a77f33a to your computer and use it in GitHub Desktop.
test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* SMS services. | |
*/ | |
"use strict"; | |
const http = require("http"); | |
const URL = require("url"); | |
/** | |
* 创建一个 Sender | |
* @param url 发送短信的 API 的 URL | |
* @param timeout 请求超时时间, 单位ms, default 500ms | |
* @param keepAlive 是否使用 keepAlive 连接池 | |
* @constructor | |
*/ | |
function SMSSender (url, timeout, keepAlive){ | |
if (!(this instanceof SMSSender)) { | |
return new SMSSender(url, timeout, keepAlive); | |
} | |
this.requesetOptions = Object.assign(URL.parse(url), { | |
"method": "POST", | |
"timeout": timeout || 500, // 500ms timeout default | |
"agent": keepAlive ? new http.Agent({"keepAlive": true}) : false // 低频用 false, 高频用 keepAliveAgent | |
}); | |
} | |
/** | |
* 发送短信, 文档: https://github.com/guanghetv/SMSNotify | |
* @param {String|String[]} phoneNum 电话号码, 大陆的可以不带 +86, 其他地区的必须有国家/地区代码 | |
* @param {String} templateName 模板名称, 请从文档末尾的列表中选择需要的 | |
* @param {Object} params 模板对应的参数表 | |
* @return {Promise} | |
*/ | |
SMSSender.prototype.sendMessage = function (phoneNum, templateName, params) { | |
let self = this; | |
return new Promise(function (resolve) { | |
let request = http.request(self.requesetOptions, resp => { | |
let body; | |
resp.on("data", chunk => body = chunk.toString()); | |
resp.on("end", () => { | |
if (resp.statusCode >= 400) { | |
resolve({"ok": false, "message": body}); | |
} else { | |
resolve({"ok": true}); | |
} | |
}); | |
}); | |
request.on("error", err => {if (!request.timeouted) console.error(err)}); | |
request.on("timeout", () => { | |
request.timeouted = true; | |
request.abort(); | |
resolve({"ok": false, "message": "request timeout"}); | |
}); | |
request.end(JSON.stringify({ | |
"phone": phoneNum, | |
"template": templateName, | |
"params": params | |
})); | |
}); | |
}; | |
module.exports = SMSSender; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "sms-sender", | |
"version": "1.0.0", | |
"description": "client for SMSNotify", | |
"main": "index.js", | |
"author": "", | |
"license": "WTFPL" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment