source: Dev/trunk/node_modules/grunt-http/tasks/http.js

Last change on this file was 517, checked in by hendrikvanantwerpen, 11 years ago

Deployment and database management now done through Grunt. Look mom, no shell\!

File size: 2.0 KB
RevLine 
[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
11var request = require('request');
12
13module.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
Note: See TracBrowser for help on using the repository browser.