Skip to content

Instantly share code, notes, and snippets.

@villesau
Created February 28, 2018 21:07
Show Gist options
  • Save villesau/d889012c003a4aca7f9aaa3997e625b1 to your computer and use it in GitHub Desktop.
Save villesau/d889012c003a4aca7f9aaa3997e625b1 to your computer and use it in GitHub Desktop.
libdef draft for request
declare module "request" {
import type { IncomingMessage } from 'http';
declare type Defaults = $Shape<{|
proxy: string
|}>;
declare class Request extends stream$Duplex {
auth(
username: ?string,
password: ?string,
sendImmediately?: boolean,
bearer?: string
): Request
}
declare class Form {
append(key: string, value: any, metadata?: Object): void
}
declare class Post extends Request {
form(Object): void,
form(): Form
}
declare type PostSpec = {|
url: string,
form?: Object,
formData?: Object
|};
declare type RequestSpec = {|
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',
preambleCRLF?: boolean,
postambleCRLF?: boolean,
uri?: string,
url?: string,
multipart?: Object | Array<Object>,
headers?: {[key: string]: string},
oauth?: {|
callback: string,
consumer_key: string,
consumer_secret: string
|},
cert?: string,
key?: string,
passphrase?: string,
ca?: string
|};
declare type RequestOptions = {|
auth: {|
user?: ?string,
pass?: ?string,
sendImmediately?: boolean,
bearer?: string
|}
|};
declare var request: {
(url: string | RequestSpec, callbackOrOptions?: Function | RequestOptions): Request,
put(url: string | RequestSpec, callbackOrOptions?: Function | RequestOptions): Request,
get(url: string | RequestSpec, callbackOrOptions?: Function | RequestOptions): Request,
post(
url: string | PostSpec,
postData?: {form?: Object},
cb?: (err: Object, httpResponse: IncomingMessage, body: Object) => void
): Post,
defaults(defaults: Defaults): typeof request
};
declare export default typeof request;
}
// @flow
import request from 'request';
import fs from 'fs';
import http from 'http';
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'));
fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))
request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))
request
.get('http://google.com/img.png')
.on('response', function(response) {
console.log(response.statusCode) // 200
console.log(response.headers['content-type']) // 'image/png'
})
.pipe(request.put('http://mysite.com/img.png'))
request
.get('http://mysite.com/doodle.png')
.on('error', function(err) {
console.log(err)
})
.pipe(fs.createWriteStream('doodle.png'))
http.createServer(function (req, resp) {
if (req.url === '/doodle.png') {
if (req.method === 'PUT') {
req.pipe(request.put('http://mysite.com/doodle.png'))
} else if (req.method === 'GET' || req.method === 'HEAD') {
request.get('http://mysite.com/doodle.png').pipe(resp)
}
}
})
http.createServer(function (req, resp) {
if (req.url === '/doodle.png') {
var x = request('http://mysite.com/doodle.png')
req.pipe(x)
x.pipe(resp)
}
})
var r = request.defaults({'proxy':'http://localproxy.com'})
http.createServer(function (req, resp) {
if (req.url === '/doodle.png') {
r.get('http://google.com/doodle.png').pipe(resp)
}
})
request.post('http://service.com/upload', {form:{key:'value'}})
// or
request.post('http://service.com/upload').form({key:'value'})
// // or
request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ })
var formData = {
// Pass a simple key-value pair
my_field: 'my_value',
// Pass data via Buffers
my_buffer: new Buffer([1, 2, 3]),
// Pass data via Streams
my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
// Pass multiple values /w an Array
attachments: [
fs.createReadStream(__dirname + '/attachment1.jpg'),
fs.createReadStream(__dirname + '/attachment2.jpg')
],
// Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
// Use case: for some types of streams, you'll need to provide "file"-related information manually.
// See the `form-data` README for more information about options: https://github.com/form-data/form-data
custom_file: {
value: fs.createReadStream('/dev/urandom'),
options: {
filename: 'topsecret.jpg',
contentType: 'image/jpeg'
}
}
};
request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
var r2 = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) {})
var form = r2.form();
form.append('my_field', 'my_value');
form.append('my_buffer', new Buffer([1, 2, 3]));
form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'});
request({
method: 'PUT',
preambleCRLF: true,
postambleCRLF: true,
uri: 'http://service.com/upload',
multipart: [
{
'content-type': 'application/json',
body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
},
{ body: 'I am an attachment' },
{ body: fs.createReadStream('image.png') }
]
},
function (error, response, body) {
if (error) {
return console.error('upload failed:', error);
}
console.log('Upload successful! Server responded with:', body);
})
request.get('http://some.server.com/').auth('username', 'password', false);
// or
request.get('http://some.server.com/', {
'auth': {
'user': 'username',
'pass': 'password',
'sendImmediately': false
}
});
// or
request.get('http://some.server.com/').auth(null, null, true, 'bearerToken');
// or
request.get('http://some.server.com/', {
'auth': {
'bearer': 'bearerToken'
}
});
request({url: 'url'}, function (error, response, body) {
// Do more stuff with 'body' here
});
{
var options = {
url: 'https://api.github.com/repos/request/request',
headers: {
'User-Agent': 'request'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(info.stargazers_count + " Stars");
console.log(info.forks_count + " Forks");
}
}
request(options, callback);
}
{
var options = {
url: 'https://api.some-server.com/',
cert: fs.readFileSync('', ''),
key: fs.readFileSync('', ''),
passphrase: 'password',
ca: fs.readFileSync('', '')
};
request.get(options);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment