Giter Site home page Giter Site logo

connect-rest's People

Contributors

asharpe-squiz avatar craigsdennis avatar gionkunz avatar gitter-badger avatar imrefazekas avatar jamespaulmuir avatar rodenis 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  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

connect-rest's Issues

new feature request for enum support

Hello again,

i have a couple of rest methods like below
rest.get('/console/pdf/:owner/:repo', function (request, content, callback) {
rest.get('/console/epub/:owner/:repo', function (request, content, callback) {
rest.get('/console/mobi/:owner/:repo', function (request, content, callback) {
rest.get('/console/html/:owner/:repo', function (request, content, callback) {

And i want to implement it with just one method like
rest.get('/console/:format/:owner/:repo', function (request, content, callback) {
format has four valid values 'pdf','epub','mobi' and 'html' it could implement as enum
var FORMATS = {
pdf : "pdf",
epub: "epub",
mobi : "mobi",
html : "html"
};

maybe the :format paramter can configured with @Format to specify that it is a enum and than it validates the passed request value against the enum and throw bad request if it is invalid otherwise the code inside the defined method will be executed.

I implemented it by my own with the following code snippet.

rest.get('/console/:format/:owner/:repo', function (request, content, callback) {
var format= FORMATS[request.parameters.format];
if(!format) {
var error = new Error('invalid format: valid fomarts are pdf, epub, mobi or html.');
error.statusCode = 400;
return callback( error );
}
callback( null, 'ok');
});

What do you think about this?

Setting context: '/' causes issues with URL

Hi guys,

I'm working through a demo site and I was defining the API url as api.meadowlark:3000. So hitting an endpoint might look like http://api.meadowlark:3000/attractions

I defined the context as:

context: '/'

but doing so forced me to have to use an extra slash in the url like this:

http://api.meadowlark:3000//attractions

Defining the context as:

context: ''

fixed the issue so I didn't have to use an extra slash. I'm not sure if it's a bug or if it's expected behavior. The code can be referenced here:

https://github.com/reybango/meadowlark/blob/master/meadowlark.js#L178

npm install error

Hy again,

i want to try the new @ feature and since today i can not build the connect-rest module.
I don't know if its a problem related to your project or not but i will also post it to npm.

Maybe you can help me out.
npm ERR! If you need help, you may report this entire log,
npm ERR! including the npm and node versions, at:
npm ERR! http://github.com/npm/npm/issues

npm ERR! System Linux 3.13.0-27-generic
npm ERR! command "/home/vagrant/.nvm/v0.10.29/bin/node" "/home/vagrant/.nvm/v0.10.29/bin/npm" "update"
npm ERR! cwd /vagrant/project/heroku-softcover
npm ERR! node -v v0.10.29
npm ERR! npm -v 1.4.14
npm ERR! path ../jade/bin/jade
npm ERR! code UNKNOWN
npm ERR! errno -1
npm ERR! error rolling back Error: ETXTBSY, unlink '/vagrant/project/heroku-softcover/node_modules/connect-rest/node_modules/lodash/dist/lodash.compat.js'
npm ERR! error rolling back [email protected] { [Error: ETXTBSY, unlink '/vagrant/project/heroku-softcover/node_modules/connect-rest/node_modules/lodash/dist/lodash.compat.js']
npm ERR! error rolling back errno: 62,
npm ERR! error rolling back code: 'ETXTBSY',
npm ERR! error rolling back path: '/vagrant/project/heroku-softcover/node_modules/connect-rest/node_modules/lodash/dist/lodash.compat.js' }

Headers have not returning

Hi i can't tune this package that it return headers. I make as wrote in a guide.
But i use it with express, as wrote in Ethan's Brown book.


const apiOptions = {
        context: '',
        domain: require('domain').create()
    };



    apiOptions.domain.on('error', function(err){
        console.log('API domain error.\n', err.stack);
        setTimeout(function(){
            console.log('Server shutting down after API domain error.');
            process.exit(1);
        }, 5000);
        server.close();
        let worker = require('cluster').worker;
        if(worker) worker.disconnect();
    });

    const rest = require('connect-rest').create(apiOptions);

    app.use(rest.processRequest());

.....

    session_start_app: function (req, content, cb) {
       return cb( null,{
           status: '201',
           message:"privet"},
           { headers: {
               ETag: "10c24bc-4ab-457e1c1f"
           } } );
    }

protectors should allow returning 400/401/403 responses.

It appears that a false return from protector causes a 404 which is not very useful in many cases.
in case protector denies access to a resource:

  1. is should be possible to return other status codes e.g. 400/401/403.
  2. also a custom response body containing a useful message would be good.

Older versions documentation

Is it possible to provide documentation for older versions such as 1.x and 2.x.
Git tags could help to get the README for a specific version.

Nothing happens, at all.

I am using the following code:

    rest.get({
        path:"/:section/:fnc/*data",
        unprotected: true
    }, handler);

    rest.get({path:"/a",unprotected:true},function(req,ct,cb){
        return cb(null, "oi");
    });

    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    app.use(rest.rester({
        context: "/api",
        monitoring: {
            populateInterval: 12000*2,
            console: true,
            listener: log.info
        }
    }));

and get nothing.

Ingwies-Macbook-Pro:BIRD3 Ingwie$ curl -v http://localhost:8080/api/a
* Adding handle: conn: 0x7fc27a004000
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7fc27a004000) send_pipe: 1, recv_pipe: 0
* About to connect() to localhost port 8080 (#0)
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /api/a HTTP/1.1
> User-Agent: curl/7.30.0
> Host: localhost:8080
> Accept: */*
> 
< HTTP/1.1 404 Not Found
< X-Response-Time: 2.902ms
< Date: Sat, 20 Sep 2014 12:33:39 GMT
< Connection: keep-alive
< Transfer-Encoding: chunked
< 
* Connection #0 to host localhost left intact

What am I doing wrong there O.o?

SyntaxError: Unexpected strict mode reserved word

/myproject/node_modules/connect-rest/lib/rest-services.js:3
let url = require('url')
^^^
SyntaxError: Unexpected strict mode reserved word
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (/app.js:10:12)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

npm ERR! System Linux 3.16.0-4-amd64
npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "start"
npm ERR! node -v v0.10.29
npm ERR! npm -v 1.4.21
npm ERR! code ELIFECYCLE
npm WARN This failure might be due to the use of legacy binary "node"

rest.rester( options ) still supprted?

Hey team,

I was reading through Ethan Brown's Node.js book where he asks readers to use connect-rest to define an api. The issue is that in the code he references rest.rester( options ) which generates the following error:

app.use(rest.rester(apiOptions));
^
TypeError: rest.rester is not a function

I looked for rester in the code for v2.9.0 but didn't see a reference to it. Is rester() a deprecated method? Asking because it's also mentioned in the docs here:

https://github.com/imrefazekas/connect-rest#context
https://github.com/imrefazekas/connect-rest#discovery-services
https://github.com/imrefazekas/connect-rest#more-examples

how to retrieve get-query stirings

Hi

Thanks first of all for this awsome library.

I try to use it as backend for an emberjs project. Some emberjs rest calls come with additional GET-parameters like this:
http://localhost:8080/data/items?ids%5B%5D=8&ids%5B%5D=9

I can get connect-rest to receive / handle this request. However, I don't have the GET-query (ids%5B%5D=8&ids%5B%5D=9) available in the request nor content parameters. How should I deal with this kind of calls?

Parameters are not getting populated

When a request comes to /api/event-log.csv?d=13&m=1&y=2014, parameters and params remain empty:

{ headers:
   { host: 'localhost:8080',
     connection: 'keep-alive',
     accept: 'application/json, text/plain, */*',
     'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTM
L, like Gecko) Chrome/31.0.1650.63 Safari/537.36',
     referer: 'http://localhost:8080/',
     'accept-encoding': 'gzip,deflate,sdch',
     'accept-language': 'en-US,en;q=0.8',
     httpVersion: '1.1',
     method: 'GET',
     originalUrl: '/api/event-log.csv?d=13&m=1&y=2014',
     clientAddress: '127.0.0.1' },
  parameters: {},
  params: {},
  files: undefined,
  session: undefined }

Here's the code that's causing this:

restSupport.get({ path: '/event-log.csv'}, function (req, content, next) {
      console.log(req);
      var response = grunt.file.read("api/event-log.csv");
      next(null, response);
   }, {contentType: 'application/csv'});

"/" default behavior for matching routes?

Hi,

Thank you for the node module. It is working great for me. Just trying get clarification around default expected behavior when matching routes, I have a declaration style like this:

        var connect = require('connect');
        var rest = require('connect-rest');
        var app = connect();

        app.use(
            rest.rester(
                {
                    context:'/'
                }
            )
        );
 rest.get(
            [{ path: '/distributions/:name', version: '>=1.0.0'}],
            function(request,content,callback){
            });

"/" is matching all routes which is suspect.

Let me know if you need any additional info.

Thanks,
@jongeho1

【bug】TypeError: winston.Logger is not a constructor

TypeError: winston.Logger is not a constructor
at Object.exports.createWinstonLogger (E:\WWW\elevator_monitor\node_modules\connect-rest\lib\logger.js:25:9)
at Object.exports.createLogger (E:\WWW\elevator_monitor\node_modules\connect-rest\lib\logger.js:5:91)
at Object.exports.rester (E:\WWW\elevator_monitor\node_modules\connect-rest\lib\connect-rest.js:483:18)
at ConnectApp.middleware (E:\WWW\elevator_monitor\gulpfile.js:178:26)
at ConnectApp.handlers (E:\WWW\elevator_monitor\node_modules\gulp-connect\index.js:189:47)
at ConnectApp.run (E:\WWW\elevator_monitor\node_modules\gulp-connect\index.js:68:10)
at new ConnectApp (E:\WWW\elevator_monitor\node_modules\gulp-connect\index.js:57:10)
at Object.server (E:\WWW\elevator_monitor\node_modules\gulp-connect\index.js:268:11)
at connectServer (E:\WWW\elevator_monitor\gulpfile.js:173:13)
at bound (domain.js:301:14)

i found a solution from https://stackoverflow.com/questions/51074805/typeerror-winston-logger-is-not-a-constructor-with-winston-and-morgan

and i changed node_module/connect-rest/lib/logger.js file like this:

微信截图_20190714215235

Get TypeError: cb is not a function

We are using connect-rest via express. We are not using connect directly and we noticed that the error cited in this issue title when we try to callback.

If we try to have "cb" below and it is always undefined and subsequent cb calls will result in the "cb is not a function".

	async function service( request, content, cb ){
	    console.log( 'Received headers:' + JSON.stringify( request.headers ) )
	    console.log( 'Received parameters:' + JSON.stringify( request.parameters ) )
	    console.log( 'Received JSON object:' + JSON.stringify( content ) )
	    console.log( 'cb:' + JSON.stringify(cb) )
	    return 'ok'
	}
	rest.get( [ { path: '/shake', version: '>=2.0.0' }, { path: '/twist', version: '>=2.1.1' } ], service )	

Domain on 'error' event listener

Hi,
When using connect-rest along with express and node.js domain functionality, as in:

var rest = require('connect-rest');
var express = require('express');

var options = {
  context: "/api",
  domain: require('domain').create(),
};

var app = express();
app.use(rest.rester(options));

Returned function restMaker adds an 'error' event listener for every request received (file lib/connect-rest.js, line 385), thus causing the following warning message:

(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.

It does not happen when domain functionality is not used though.

ES6 Array prototype functions are enumerable

var rest = require('connect-rest');

var myArray = ['element1', 'element2'];
for(var i in myArray){
    console.log(myArray[i]);
}

expected output:

element1
element2

actual output:

element1
element2
[Function]
[Function]
[Function]
[Function]

Missing: HTTP OPTIONS method

I'm trying to do Preflighted CORS Requests and I don't have access to HTTP OPTIONS while using connect-rest:

TypeError: Cannot call method 'find' of undefined.
  at getRouterMatching (...lib/connect-rest.js:384:15)

In order to make Preflighted CORS requests, I believe I'd need connect-rest to implement the OPTIONS method. Is there an obvious reason this method wasn't implemented? If not, is there anything stopping it from being implemented?

I can make that change myself and I could send out a Pull Request, but I want to understand the situation fully. Node.js and connect-rest are relatively new to me.

Thanks

How to get a matched route to fallthrought to the next middleware?

When I do something like:

rest.get('/person/:id', function(req, res, next) {
    const toUrl = req.url.replace(rest.context, rest.options.forward);
    req.url = toUrl;
    next();
});

The code is not really that important, it's all about the next-call at the end.

I expect the next (connect) middleware to be invoked, but that never happens. I'm guessing connect-rest does something to block this functionality by wrapping connect's next-callback in their own.

How would I get connect-rest to match and then fall through to the next layer of middleware?

Having a problem with path resolution

I have the following snippet of code:

rest.get( { path : '/ships', unprotected: true }, function(req, content, cb){
    Ship.find({}, function(err, ships){
        if (err) return cb({error:'Internal Error'});
        // cb(null, ships);
        cb(null, ships.map(function(ele) {
            return {
                '_id' : ele._id,
                'name' : ele.name,
                'displayName' : ele.displayname,
                'shipManufactor' : ele.shipManufacturer,
                'enabledInSSB' : ele.enabledInSSB,
                'deprecated' : ele.deprecated
            };
        }));
    });
});
rest.get( { path : '/ships/id/:id', unprotected : true }, function(req, content, callback){
    console.log("Looking for ship ID " + req.params.id);
    Ship.findById(req.params.id, function(err, ship){
        if (err) {
            if (err.name == 'CastError') {
                var error = new Error("Unable to parse given ID -- Check that the given ID is properly formatted and the correct number of characters");
                error.statusCode = 500;
                return callback(error, {'result' : err});
            }
            var error = new Error("An internal database error occured");
            error.statusCode = 500;
            return callback(error, {'result' : err});
        }
        if (ship === null) {
            var error = new Error('Document not found');
            error.statusCode = 404;
            return callback(error);
        }
        else {
            callback(null, ship);
        }
    });
});

Defining two paths, one "/ships" and one "/ships/id/:id" - yet whenever I call just plain "/ships" it is the SECOND one, "/ships/id/:id" that is firing! Why would this be?

Hello world example needed sorely

Hey! I tried several hours today to get a hello world example running, but no luck (not even any errors), and yet the API and functionality is exactly what's needed for an internal service I have in mind for work.

const fs = require('fs')
const path = require('path')
const http = require('http')
const connect = require('connect')
const bodyParser = require('body-parser')
const Rest = require('connect-rest')

const PORT = process.env.PORT || 8000

// initial configuration of connect-rest. all-of-them are optional.
// default context is /api, all services are off by default
const rest = Rest.create({
	context: '/api',
	logger: { file: 'mochaTest.log', level: 'debug' },
	//apiKeys: [ '849b7648-14b8-4154-9ef2-8d1dc4c2b7e9' ],
	discover: { path: 'discover', secure: false },
	// proto: { path: 'proto', secure: true }
})
const app = connect()
	.use(bodyParser.urlencoded({ extended: true }))
	.use(bodyParser.json())
	.use(rest.processRequest())

// defines a few sample rest services
const debug = (request, content, callback)=>{ 
	console.log( 'Received headers:' + JSON.stringify( request.headers ))
	console.log( 'Received parameters:' + JSON.stringify( request.parameters ) )
	console.log( 'Received JSON object:' + JSON.stringify( content ) )
	callback(null, 'ok')
}
rest.get('/books/:title/:chapter', debug)
rest.post( { path: '/make', version: '>=1.0.0' }, debug)
rest.post( [ '/act', '/do' ], debug)
rest.post( [ { path: '/shake', version: '>=2.0.0' }, { path: '/twist', version: '>=2.1.1' } ], debug)

http.createServer(app).listen(PORT, function () {
	console.log('Running on http://localhost:'+PORT)
})

Setting header in options doesn't work

Following the example here:

headers: {

The headers that are passed don't actually get set. I attempted to set the Access-Control-Allow-Origin header on a server running on one port and access the end-points from a server running on another port. The response header is not set.

Could possibly be related to this commented out line:

// res.writeHead( statusCode, headers )

return binary file content

Hello,

i found your great rest framework and want to use to return binary file content instead of json or xml. Is that supported now by return a filestream or file object?

great work so far

About the support for the "cors" Node module

I want to know whether "connect-rest" support "cors" like this:

var cors = require('cors');
var corsOptions = {
origin: 'http://...'
};
rest.post('/books/add', cors(corsOptions), functionN0 );

When I try above, got this Error:
TypeError: Object # has no method 'setHeader'
at applyHeaders (/Users/DSS/Dev/GitDoc/pow/node_modules/cors/lib/index.js:146:15)

How to update list of API keys during runtime?

I want my users to be able to revoke and regenerate API keys on the fly, but it looks like the API keys are defined in connect-rest only when the module is first initialized. How would I go about changing them during runtime? Is it safe to simply call rester(options) again with new options?

Setting context via options doesn't work if context is blank

When calling rest.rester(), if you set the value of options.context to a blank string, or leave it out of the options object altogether, the internal context is set to '/api'. So:

rest.rester({context: ""});  // context is set to '/api'

rest.rester({logger: "connect-rest"});  // context is set to '/api'

This works, however:

rest.context('');  // context is set to ''

The problem occurs on line 209 of connect-rest.js:

exports.context( options.context || '/api' );

I'd submit a pull request except that I can't figure out what the intent of that code is. ;-)

-Steve

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.