Giter VIP home page Giter VIP logo

grunt-connect-prism's Introduction

grunt-connect-prism

NPM version Build Status Dependency Status devDependency Status

Record, mock, and proxy HTTP traffic using the connect-prism middleware.

Getting Started

This plugin requires Grunt ~0.4.1 and the grunt-contrib-connect ~0.7.1 plugin to already be installed.

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

npm install grunt-connect-prism --save-dev

One the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

grunt.loadNpmTasks('grunt-connect-prism');

Overview

This grunt plugin is a wrapper around the connect-prism middleware.

Prism is similar to the Ruby project VCR.

The purpose of this plugin is to provide an easy way for front end developers to record HTTP responses returned by their API (or some other remote source) and then be able replay the responses in the future. It's basically an HTTP cache, but for developers working on a Single Page Application (SPA).

It's useful for mocking complex & high latency API calls during development. It's also useful when writing e2e tests for your SPA only, removing the server from the equation. This results in much faster execution of your e2e test suite.

Prism works by adding a custom connect middleware to the connect server provided by the grunt-contrib-connect plugin.

Modes

There are currently 4 supported modes of operation.

Record

The record mode will allow you to both record and proxy all HTTP traffic for a certain endpoint on your connect development server. For example, if in production your API sits at an endpoint /api then you may be currently proxying requests to a server you're hosting locally on another port or to an integration machine somewhere else. You may have also attempted to mock out services that make HTTP calls in your client side code itself. While in record mode you can navigate your application and trigger all the types of API calls you would like to have recorded. Prism will then listen for responses and serialize them to disk. When you want to read these responses instead of proxying traffic to the real server you shutdown and switch to the 'mock' mode.

To make mocks more readable, responses with a content-type of json or javascript will have their data stringified as an object. If the content-type is anything other than json or if stringification fails then it falls back to a string.

If the server returns a compressed response (gzip or deflate are supported), then prism will decompress the payload when recording the response.

Example mock generated:

{
  "requestUrl": "/api/ponies",
  "contentType": "application/json",
  "statusCode": 200,
  "data": {
    "text": "my little ponies"
  }
}

Mock

The mock (read) mode will listen for requests to a certain endpoint. When a request matches an endpoint it will attempt to find a previously recorded response in the directory you defined mocks to be saved in (./mocks by default).

If a matching response is not found then prism will return a 404. Prism will also create a mock during a 404. This is useful when you want to mock API endpoints that may not exist yet. To avoid having the subsequent request from returning the generated empty mock, the file has a .404 extension. To use the mock, populate it with the appropriate values and remove the .404 extension. This feature was contributed by Miloš Mošovský.

Mock & Record

As its name implies this operation will mock and record. This mode will first attempt to load a mock if one exists. If a mock does not exist it will then proxy the request and record the response instead of returning a 404.

Proxy

And finally, prism supports simple proxying in much the same way as the grunt-connect-proxy plugin works. In fact, this plugin is heavily inspired by that project. While in proxy mode, listening events for recording and mocking are disabled.

Adapting the "connect" task

Adding the middleware

This configuration is based on a modification to the connect middleware configuration that the yeoman angular-generator will create.

connect: {
  livereload: {
    options: {
      middleware: function(connect) {
        return [
          require('grunt-connect-prism/middleware'),
          connect.static('.tmp'),
          connect().use(
            '/bower_components',
            connect.static('./bower_components')
          ),
          connect.static(appConfig.app)
        ];
      }
    }
  }
}

Configuration

In your project's Gruntfile, add a section named prism.

Adding prism configuration.

You can add all the options in the root task options, in a target options, or a mix of both (where the target options will inherit from the root options). If only the root prism options are provided than a prism instance with the name 'default' will be created.

i.e)

prism: {
  options: {
    mode: 'record',
    host: 'localhost',
    port: 8090,
    context: '/api'
  }
}

Multiple targets

You can create multiple prism targets in the standard convention of grunt configuration. grunt-connect-prism will create a directory in the mocksPath directory named after the target.

i.e.)

prism: {
  options: {
    host: 'localhost',
    port: 8090,
    https: true,
    mocksPath: './stubs',
    useApi: true
  },
  server: {
    options: {
      mode: 'record',
      context: '/api'
    }
  }
}

Running prism

Typically you will want to run your prism task while you're running your development server, or while e2e tests are running. There are several different ways to add prism tasks to the grunt task queue.

Usage)

'prism[:target[:mode]]'

If 'prism' is executed by itself then all prism targets will be created.

If a target is supplied (i.e. 'prism:targetOne') then only that prism target instance will be created.

If a target and mode are supplied (i.e. 'prism:targetOne:record') then only that prism target instance will be created and will be in the record mode.

Basic grunt serve example.

grunt.registerTask('serve', function () {
  grunt.task.run([
    'clean:server',
    'compass:server',
    'prism',
    'livereload-start',
    'connect:livereload',
    'open',
    'watch'
  ]);
});

Target and mode override example (i.e. grunt serve:targetOne:record).

grunt.registerTask('serve', function (target, prismMode) {
  grunt.task.run([
    'clean:server',
    'compass:server',
    'prism:' + target + ':' + prismMode, /* see mode configuration for more details */
    'livereload-start',
    'connect:livereload',
    'open',
    'watch'
  ]);
});

Options

Options pass through directly to connect-prism. See Options section in connect-prism.

API features

The API can be enabled in the root prism configuration. The API is disabled by default.

prism: {
  options: {
    useApi: true
  }
}

See the API features section in connect-prism for more details.

Release History

  • 1.0.0 Use connect-prism 1.0.0. Added API capabilities.
  • 0.7.6 Use connect-prism 0.7.5 to fix socket hang up issue by handling aborted requests appropriately (issue #15). Issue #527 from node-http-proxy project.
  • 0.7.4 Support 'default' instance. Re-factor tests.
  • 0.7.3 Upgrade to connect-prism 0.7.3.
  • 0.7.1 Upgrade to connect-prism 0.7.1.
  • 0.7.0 Upgrade to connect-prism 0.7.0.
    Fix legacy middleware call.
  • 0.6.0 Upgrade to connect-prism 0.6.0.
    Fix spec to use PrismManager.
  • 0.5.0 Upgrade to connect-prism 0.5.0.
  • 0.4.2 Upgrade to connect-prism 0.4.2.
  • 0.4.1 Upgrade to connect-prism 0.4.1.
  • 0.3.0 Use connect-prism core library.
  • 0.2.2 Support change origin.
  • 0.2.1 Fixed record mode and tests so we don't release broken again!
  • 0.2.0 Support 'cassettes' by putting mocks into directories named after target.
    Use http-proxy 0.10.4 to workaround around socket hangup issues in 1.1.4.
  • 0.1.1 Stop recording all response headers.
    Only capture content-type.
  • 0.1.0 Initial release

grunt-connect-prism's People

Contributors

milosmosovsky avatar seglo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

grunt-connect-prism's Issues

Problem with middleware

I'm making some tests and trying to use this tool, that by the way is a great one. Will save me a lot of time.
So talking about the issue, when I configured the middleware for live reload as it is in the sample app:

livereload: {
                options: {
                    open: true,
                    middleware: function (connect) {
                        return [
                            require('grunt-connect-prism/middleware')
                            connect.static('.tmp'),
                            connect().use(
                                '/bower_components',
                                connect.static('./bower_components')
                            ),
                            connect.static(appConfig.app)
                        ];
                    }
                }
            }

and run grunt serve, the application start and run the code that is in the dist folder.
The solution was to move the require('grunt-connect-prism/middleware') to be the last instruction in the array:

livereload: {
                options: {
                    open: true,
                    middleware: function (connect) {
                        return [
                            connect.static('.tmp'),
                            connect().use(
                                '/bower_components',
                                connect.static('./bower_components')
                            ),
                            connect.static(appConfig.app),
                            require('grunt-connect-prism/middleware')
                        ];
                    }
                }
            }

I don't know the real reason for that, so that's why I'm writing here. This could be happening with others.

changeOrigin is not supported in 1.0.1

This could be easly supported by adding the following line after line 125 in connect-prism/lib/prism.js

changeOrigin: config.changeOrigin || false, //adds changeOrigin option

Grunt connect prism not recording

Hi,

This maybe an issue on my part but i need help!

I want to record responses that my backend api returns. This API is deployed on tomcat locally at http://localhost:8084/locationsapi.

I created a grunt angular project using yeoman.
I followed your instructions to add in the prism config to the gruntFile.js.

When I run grunt:serve I see the below log:
info: Prism created for: /locationsapi to localhost:8084

But when I hit an endpoint I dont see any file written to mock directory.
Example endpoint:
http://localhost:8084/locationsapi/v1/services

Am I doing something wrong?

I have attached my gulpFile.

Grunt version is grunt v0.4.5
prism version is "grunt-connect-prism": "^1.0.3"

Thanks,
Shane.

// Generated on 2015-06-30 using generator-angular 0.11.1
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
var path = require('path');

module.exports = function (grunt) {

  grunt.loadNpmTasks('grunt-connect-prism');


  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: 'dist'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      styles: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
        tasks: ['newer:copy:styles', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              require('grunt-connect-prism/middleware'),
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect().use(
                '/app/styles',
                connect.static('./app/styles')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Setup one prism
    prism: {
      options: {
        mode: 'record',
        host: 'localhost',
        port: 8084,
        context: '/locationsapi'
      }
    },



    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git{,*/}*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      server: {
        options: {
          map: true,
        },
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath:  /\.\.\//
      },
      test: {
        devDependencies: true,
        src: '<%= karma.unit.configFile %>',
        ignorePath:  /\.\.\//,
        fileTypes:{
          js: {
            block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
              detect: {
                js: /'(.*\.js)'/gi
              },
              replace: {
                js: '\'{{filePath}}\','
              }
            }
          }
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '<%= yeoman.dist %>/styles/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat', 'uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: [
          '<%= yeoman.dist %>',
          '<%= yeoman.dist %>/images',
          '<%= yeoman.dist %>/styles'
        ]
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // ng-annotate tries to make the code safe for minification automatically
    // by using the Angular long form for dependency injection.
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: '*.js',
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'styles/fonts/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }, {
          expand: true,
          cwd: 'bower_components/bootstrap/dist',
          src: 'fonts/*',
          dest: '<%= yeoman.dist %>'
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'copy:styles'
      ],
      test: [
        'copy:styles'
      ],
      dist: [
        'copy:styles',
        'imagemin',
        'svgmin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    }
  });


  grunt.registerTask('serve', 'Compile then start a connect web server', function (target, prismMode) {

    var prismTask = 'prism:serve';

    if (prismMode) {
      prismTask = prismTask + ':' + prismMode;
    }


    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'autoprefixer:server',
       prismTask,
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'wiredep',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};

Useless filenames.

Why are the file names outputted as hashes? Making a point in the README about how the contents are saved is useless if you can't find the request in the myriad of random characters.

Example:

|~mocks/
| |~_prism/
| | `~local/
| |   |-0032833dec7ae5dbe16c901a27b99b1f63f14846.json
| |   |-0259ce6a343e29611716b04c63fd26379c5bbe44.json
| |   |-032462556b77c5025f4599ce9cb46de7dc653b3a.json
| |   |-046c4680244657272493d49fc7c1779da4e20198.json
| |   |-06481e693ec1f12bc4f421fe393675a063fea10a.json
| |   |-06bf2a97a492ae6ebd58a7c39a94b57aad8ab1a2.json
| |   |-06f1d0bbb1739a4623bf1517582fcfec70d22f94.json
| |   |-06f5624742e6ca409e12c96bfa7329122a4f7525.json
| |   |-0929d28333a9b23c8c2e1a12c78d10fef48f8150.json
| |   |-0af00204a5ba45aafcc9b057bab92c69dc38edf1.json
| |   |-0b4e0b35dafdd86e4063c314816d8443f68486fd.json
| |   |-0bb80d2adc6e082fad8d2691cbb40957ed6b913c.json
| |   |-0d3bd8bc480e35528c1b3cfd303185ed23383a5f.json
| |   |-0f439dd00a51a62fec3de8ecc5ca676bf4f127d4.json
| |   |-11be9a2a15ef9cf9beaf2ddba0575a8e3f0f0d1c.json
| |   |-12a55a71ef18df75aef47fd58db10b9fd59d1c9d.json
| |   |-1314687bccdefe3c889865a7e970c6d0e02e8ee8.json

Can't use multiple proxies

Is it possible to use multiple proxies? I have tried but only my first proxy seems to work, while my second one always seems to be ignored.

first: {
  options: {
    mode: 'proxy',
    mocksPath: './mocks',
    context: '/apidecorator',
    host: '10.1.81.6',
    port: 8080,
    https: false,
  },
second: {
  options: {
    mode: 'proxy',
    mocksPath: './mocks',
    context: '/api',
    host: 'localhost',
    port: 9090,
    https: false,
  }
},

Disable log output

I would like to be able to disable all the output being logged to the console. Especially for usage in test runners where it garbles the test runner output.

CI Build fails because of dependecies

I'm getting this error when I run npm install

I investigated and found that connect-prism depends on di.js which depends on traceur-compiler. connect-prism is at version 1.0.0 while grunt-connect-prism is ^0.7.6 and other dependencies are not up-to-date.

It would be great if dependencies were updated!


[16:51:11][npm install] npm ERR! notarget No compatible version found: traceur@'vojtajina/traceur-compiler#add-es6-pure-transformer-dist'
[16:51:11][npm install] npm ERR! notarget Valid install targets:
[16:51:11][npm install] npm ERR! notarget ["0.0.1","0.0.2","0.0.3","0.0.4","0.0.5","0.0.6","0.0.7","0.0.8","0.0.9","0.0.10","0.0.11","0.0.12","0.0.13","0.0.14","0.0.15","0.0.16","0.0.17","0.0.18","0.0.19","0.0.20","0.0.21","0.0.22","0.0.23","0.0.24","0.0.25","0.0.27","0.0.28","0.0.29","0.0.30","0.0.31","0.0.32","0.0.33","0.0.34","0.0.35","0.0.36","0.0.37","0.0.38","0.0.39","0.0.40","0.0.41","0.0.42","0.0.43","0.0.44","0.0.45","0.0.46","0.0.47","0.0.48","0.0.49","0.0.50","0.0.51","0.0.52","0.0.53","0.0.54","0.0.55","0.0.56","0.0.57","0.0.58","0.0.59","0.0.60","0.0.61","0.0.62","0.0.63","0.0.64","0.0.65","0.0.66","0.0.67","0.0.68","0.0.69","0.0.70","0.0.71","0.0.72","0.0.73","0.0.74","0.0.75","0.0.76","0.0.77","0.0.78","0.0.79","0.0.80","0.0.81"]
[16:51:11][npm install] npm ERR! notarget
[16:51:11][npm install] npm ERR! notarget This is most likely not a problem with npm itself.
[16:51:11][npm install] npm ERR! notarget In most cases you or one of your dependencies are requesting
[16:51:11][npm install] npm ERR! notarget a package version that doesn't exist.
[16:51:11][npm install]
[16:51:11][npm install] npm ERR! System Windows_NT 6.2.9200
[16:51:11][npm install] npm ERR! command "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "install"
[16:51:11][npm install] npm ERR! cwd C:\BuildAgent\work\39552a5b2b8d5b22
[16:51:11][npm install] npm ERR! node -v v0.10.35
[16:51:11][npm install] npm ERR! npm -v 1.4.28
[16:51:11][npm install] npm ERR! code ETARGET
[16:51:11][npm install] npm
[16:51:11][npm install] Process exited with code 1

Fatal error: socket hang up

When upgrading from 0.7.1 to 0.7.3 I started getting "Fatal error: socket hang up�" between my two test files (using grunt-mocha-casperjs). Upgrading to 0.7.4 doesn't fix it, but downgrading to 0.7.1 fixes the issue.

Seems very similar to this issue: drewzboto/grunt-connect-proxy#70

Here's a build log with the error: https://travis-ci.org/spotify/puppetexplorer/builds/36571828#L290
And a previous working build: https://travis-ci.org/spotify/puppetexplorer/builds/35206683

Feature Request: Runtime configuration options

First off, I love this tool!

As I've used it, a use case that I've come up with is to mock different scenarios of the same call. While this could be accomplished through multiple targets, starting up and shutting down grunt, segregating protractor specs and adding targets for each new case is unappealing.

It would be awesome to have the middleware pick up on certain context or headers or something that allows run-time configuration of the following options:

  • mock location (so that multiple sets of mocks can be used)
  • delay
  • https

I'm sure this certainly isn't high priority, but I thought I would throw it out there.

Thanks again for the great project!

Proxy Rewrite

For my use case I need to rewrite proxy requests to our backend. For example...

/api/endpoint proxies to api.myserver.com/endpoint
/apiu/endpoint proxies to api-u.myserver.com/endpoint

I'm currently using grunt-connect-proxy because it will rewrite proxy requests with a rewrite option.

rewrite: {
        '^/removingcontext': '',
        '^/changingcontext': '/anothercontext'
    }

So here is my current setup in grunt-connect-proxy...

"context": "/api",
"host": "api.myserver.com",
"port": 443,
"https": true,
"changeOrigin": true,
"xforward": false,
"rewrite": {
    "^/api": ""
}

Love the goals of connect-prism and would like to start using it if I can rewrite proxy requests.

Am I correctly using prism?

Hi

I was looking for a stub-server and came across your plugin which at first sight looked exactly like something that would serve my needs. But now I'm not sure anymore.

Allow me to explain my setup and problem I'm trying to solve.

  1. I want to develop my AngularJS front-end separately from my back-end.
  2. Ideally I'd want to just replace my back-end with something that acts as if it is a real back-end, but just returns dummy data. Data that would be valid and coming out of the actual back-end but doesn't access the back-end at all.

Here's what I thought prism would do:

  1. Look for .json files in a configurable directory to match Http requests and serve responses from a .json file.
  2. Actually start a server through connects middleware on a configurable port that would catch and (re-)route requests.

What I'm noticing though, is:

  1. After I grunt serve, prism has 'created' a server Prism created for: /api to localhost:8090.
  2. When I curl to http://localhost:8090/api I get a connection refused.

Relevant set-up information:
In Gruntfile.js (after generating with yo angular and manually adding prism)

  require('load-grunt-tasks')(grunt);
...
    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'autoprefixer',
      'prism',
      'connect:livereload',
      'watch'
    ]);
...
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              require('grunt-connect-prism/middleware'),
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
...
    prism: {
      options: {
        mocksPath: './stubs',
        host: 'localhost',
        port: 8090,
        https: false,
        changeOrigin: true
      },
      server: {
        options: {
          mode: 'mockrecord',
          context: '/api'
        }
      }
    },

All of my $resource calls are going to http://localhost:8090, e.g. http://localhost:8090/api/v1/categories.
Folder structure looks like this:

/app
  /scripts
/stubs
  /server
    categoriesStub.json
  categoriesStub.json
Gruntfile.js

categoriesStub.json contains this:

{
  "requestUrl": "/api/v1/categories/categories.json",
  "contentType": "application/json",
  "statusCode": 200,
  "data": 
[
  {
  "id" : "1",
  "name": "cat1"
  },
  {
  "id" : "2",
  "name": "cat2"
  }
]
},
{
  "requestUrl": "/api/v1/categories/1",
  "contentType": "application/json",
  "statusCode": 200,
  "data": 
{
"id" : "1",
"name": "cat1"
}
}

Sorry about these numbered lists, I can't seem to post stuff without feeling the need to use them. :s

Invalid SSL certs return mysterious errors

When proxying to a 3rd party with an invalid SSL cert very little information is returned to the client. In my test case, just a 500 and a response of "An error has occurred: {}".

Question: Is it possible to have multiple "prism's" instantiated?

I just stumbled across this tool yesterday, in keeping with my look before coding anything practice, and WOW, this is a very useful tool, that is easy to use, too... I already have it working well in my dev environment for a backbone app I am working on!

Congratulations, and thank you so much for your efforts in this area :toast:

I am curious as to how I would handle multiple endpoints in a single grunt server/connect task?

Is that possible today?

If not, any ideas on how that might be implemented? I am new to grunt, and node, but not JS, and I am really loving this new dev tool-chain for web developers, so I may be able to implement it for you, if it isn't already, and if you could point me in the right direction.

Again, thank you very much for this very useful tool, it is much appreciated!

t

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.