[517] | 1 | /* |
---|
| 2 | * grunt-http |
---|
| 3 | * https://github.com/johngeorgewright/grunt-contrib-http |
---|
| 4 | * |
---|
| 5 | * Copyright (c) 2013 John Wright |
---|
| 6 | * Licensed under the MIT license. |
---|
| 7 | */ |
---|
| 8 | |
---|
| 9 | 'use strict'; |
---|
| 10 | |
---|
| 11 | var request = require('request'); |
---|
| 12 | |
---|
| 13 | module.exports = function (grunt) { |
---|
| 14 | |
---|
| 15 | function responseHandler (done, dest, ignoreErrors) { |
---|
| 16 | return function (error, response, body) { |
---|
| 17 | |
---|
| 18 | response = response || { statusCode: 0 }; |
---|
| 19 | |
---|
| 20 | grunt.verbose.subhead('Response'); |
---|
| 21 | |
---|
| 22 | if (error && !ignoreErrors) { |
---|
| 23 | grunt.fail.fatal(error); |
---|
| 24 | return done(error); |
---|
| 25 | } else if (!ignoreErrors && (response.statusCode < 200 || response.statusCode > 299)) { |
---|
| 26 | grunt.fail.fatal(response.statusCode); |
---|
| 27 | return done(response.statusCode); |
---|
| 28 | } |
---|
| 29 | |
---|
| 30 | grunt.log.ok(response.statusCode); |
---|
| 31 | grunt.verbose.writeln(body); |
---|
| 32 | |
---|
| 33 | if (dest) { |
---|
| 34 | grunt.file.write(dest, body); |
---|
| 35 | } |
---|
| 36 | |
---|
| 37 | done(); |
---|
| 38 | }; |
---|
| 39 | } |
---|
| 40 | |
---|
| 41 | function readFile(filepath) { |
---|
| 42 | return grunt.file.read(filepath); |
---|
| 43 | } |
---|
| 44 | |
---|
| 45 | grunt.registerMultiTask('http', 'Sends a HTTP request and deals with the response.', function () { |
---|
| 46 | |
---|
| 47 | var options = this.options({ |
---|
| 48 | ignoreErrors: false, |
---|
| 49 | sourceField: 'body' |
---|
| 50 | }), |
---|
| 51 | done = this.async(), |
---|
| 52 | sourceField = options.sourceField, |
---|
| 53 | sourcePath = sourceField.split('.'), |
---|
| 54 | sourceKey = sourcePath.pop(), |
---|
| 55 | sourceObj = options; |
---|
| 56 | |
---|
| 57 | sourcePath.forEach(function (key) { |
---|
| 58 | sourceObj = sourceObj[key]; |
---|
| 59 | }); |
---|
| 60 | |
---|
| 61 | if (this.files.length) { |
---|
| 62 | this.files.forEach(function (file) { |
---|
| 63 | var dest = file.dest, |
---|
| 64 | contents; |
---|
| 65 | |
---|
| 66 | if (file.src) { |
---|
| 67 | contents = file.src.map(readFile).join('\n'); |
---|
| 68 | sourceObj[sourceKey] = contents; |
---|
| 69 | } |
---|
| 70 | |
---|
| 71 | grunt.verbose.subhead('Request'); |
---|
| 72 | grunt.verbose.writeln(JSON.stringify(options, null, 2)); |
---|
| 73 | |
---|
| 74 | request(options, responseHandler(done, dest, options.ignoreErrors)); |
---|
| 75 | }); |
---|
| 76 | } else { |
---|
| 77 | request(options, responseHandler(done, null, options.ignoreErrors)); |
---|
| 78 | } |
---|
| 79 | |
---|
| 80 | }); |
---|
| 81 | |
---|
| 82 | }; |
---|
| 83 | |
---|