Skip to content

Commit

Permalink
fun!
Browse files Browse the repository at this point in the history
  • Loading branch information
brianleroux committed Oct 30, 2016
1 parent 86a9275 commit 9b8e74a
Show file tree
Hide file tree
Showing 7 changed files with 144 additions and 90 deletions.
48 changes: 48 additions & 0 deletions _get.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
var http = require('http')
var https = require('https')
var url = require('url')

module.exports = function GET(options, callback) {

// require options.url or fail noisily
if (!options.url) {
throw Error('options.url required')
}

// parse out the options from options.url
var opts = url.parse(options.url)
var method = opts.protocol === 'https:'? https.get : http.get

opts.rejectUnauthorized = false
opts.agent = false
opts.headers = options.headers || {}
opts.headers['User-Agent'] = opts.headers['User-Agent'] || 'tiny-http'
opts.headers['Content-Type'] = opts.headers['Content-Type'] || 'application/json'

// make a request
method(opts, res=> {

var rawData = ''
var statusCode = res.statusCode
var contentType = res.headers['content-type']
var isJSON = contentType.startsWith('application/json')

if (statusCode !== 200) {
callback(Error(`GET failed with: ${statusCode}`))
res.resume()
return
}

res.setEncoding('utf8')
res.on('data', chunk=> rawData += chunk)
res.on('end', x=> {
try {
var parsedData = isJSON? JSON.parse(rawData) : rawData
callback(null, parsedData)
}
catch (e) {
callback(e.message)
}
})
}).on('error', e=> callback(Error(e.message)))
}
59 changes: 59 additions & 0 deletions _post.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
var qs = require('querystring')
var http = require('http')
var https = require('https')
var url = require('url')

module.exports = function POST(options, callback) {

// require options.url or fail noisily
if (!options.url) {
throw Error('options.url required')
}

// parse out the options from options.url
var opts = url.parse(options.url)
var method = opts.protocol === 'https:'? https.request : http.request

opts.method = 'POST'
opts.rejectUnauthorized = false
opts.agent = false
opts.headers = options.headers || {}
opts.headers['User-Agent'] = opts.headers['User-Agent'] || 'tiny-http'
opts.headers['Content-Type'] = opts.headers['Content-Type'] || 'application/json'
// opts.headers['Content-Type'] = 'application/x-www-form-urlencoded'
var reqJSON = opts.headers['Content-Type'] === 'application/json'
var postData = reqJSON? JSON.stringify(options.data || {}) : qs.stringify(options.data || {})

// make a POST request
var req = method(opts, res=> {

var rawData = ''
var statusCode = res.statusCode
var contentType = res.headers['content-type']
var isJSON = contentType === 'application/json'

if (statusCode !== 200) {
callback(Error(`GET failed with: ${statusCode}`))
res.resume()
return
}

res.setEncoding('utf8')
res.on('data', chunk=> rawData += chunk)
res.on('end', x=> {
try {
var parsedData = isJSON? JSON.parse(rawData) : rawData
callback(null, parsedData)
}
catch (e) {
callback(e.message)
}
})
})

req.on('error', e=> callback(Error(e.message)))

req.write(postData)

req.end()
}
78 changes: 4 additions & 74 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,77 +1,7 @@
var http = require('http')
var https = require('https')
var url = require('url')
var _get = require('./_get')
var _post = require('./_post')

function exec(httpMethod, options, callback) {

// require options.url or fail noisily
if (!options.url) {
throw Error('options.url required')
}

// parse out the options from options.url
var opts = url.parse(options.url)
var method = opts.protocol === 'https:'? https.get : http.get

// ignore warnings about dns
opts.rejectUnauthorized = false
opts.agent = false
opts.timeout = 3000
opts.headers = options.headers || {}

if (httpMethod === 'POST') {
method = opts.protocol === 'https:'? https.request : http.request
opts.method = 'POST'
opts.headers['Content-Type'] = 'application/x-www-form-urlencoded'
}

// set a User-Agent (Github requires this for example)
if (!opts.headers['User-Agent']) {
opts.headers['User-Agent'] = 'tiny-http'
}

// if json and no Content-Type set then use application/json
if (options.json && typeof opts.headers['Content-Type'] === 'undefined') {
opts.headers['Content-Type'] === 'application/json'
}

console.log(opts)

// make a request
method(opts, res=> {

var rawData = ''
var statusCode = res.statusCode
// var contentType = res.headers['content-type']

if (statusCode !== 200) {
callback(Error(`GET failed with: ${statusCode}`))
res.resume()
return
}

res.setEncoding('utf8')
res.on('data', chunk=> rawData += chunk)
res.on('end', x=> {
try {
var parsedData = options.json? JSON.parse(rawData) : rawData
callback(null, parsedData)
}
catch (e) {
callback(e.message)
}
})
}).on('error', e=> callback(Error(e.message)))
}

// - opts: url
module.exports = {

get(options, callback) {
exec('GET', options, callback)
},

post(options, callback) {
exec('POST', options, callback)
}
get: _get,
post: _post,
}
9 changes: 4 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
{
"name": "tiny-http",
"name": "tiny-json-http",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "tape test-* | tap-spec"
},
"keywords": [],
"author": "",
"license": "ISC",
"author": "Brian LeRoux <b@brian.io>",
"license": "Apache-2.0",
"devDependencies": {
"body-parser": "^1.15.2",
"express": "^4.14.0",
"tap-spec": "^4.1.1",
"tape": "^4.6.2"
Expand Down
23 changes: 21 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,22 @@
minimalist http.get and http.post
# tiny-json-http

- symmetry with mikeal/request
Minimalist `HTTP` client for `GET` and `POST`ing `JSON` payloads

- Zero dependencies: perfect for AWS Lambda
- Sane default: assumes buffered JSON responses
- System symmetry: Node style errback API

```bash
npm i tiny-json-http --save
```

### api

- `tiny.get(options, callback)`
- `tiny.post(options, callback)`

### options

- `url` *required*
- `data` only used by `http.post`
- `headers` key/value map used for headers
6 changes: 1 addition & 5 deletions test-get.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ test('can get a url', t=> {
test('can get json', t=> {
t.plan(2)
var url = 'https://api.github.com/'
var json = true
tiny.get({url, json}, function __json(err, result) {
tiny.get({url}, function __json(err, result) {
if (err) {
t.fail(err)
}
Expand All @@ -53,6 +52,3 @@ test('get fails gracefully', t=> {
}
})
})

// handles post json:true
// handles post form
11 changes: 7 additions & 4 deletions test-post.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
var test = require('tape')
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var tiny = require('./')
var server

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))

app.post('/', (req, res)=> {
res.json({ok:true}).end()
res.json(Object.assign(req.body, {ok:true}))
})

test('startup', t=> {
Expand All @@ -18,9 +22,8 @@ test('startup', t=> {
test('can post', t=> {
t.plan(1)
var url = 'http://localhost:3000/'
var json = true
tiny.post({url, json}, function __posted(err, result) {
console.log('got something', err, result)
var data = {a:1, b:new Date(Date.now()).toISOString()}
tiny.post({url, data}, function __posted(err, result) {
if (err) {
t.fail(err)
}
Expand Down

0 comments on commit 9b8e74a

Please sign in to comment.