如何在Node.js中最好地创建RESTful API [英] How to best create a RESTful API in Node.js

查看:136
本文介绍了如何在Node.js中最好地创建RESTful API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node的初学者(通常都是后端Web开发),我已经开始在Node中编写一个RESTful API。有一些事情我想让我的头脑。



我的应用程序使用Express和Mongoose,而我正在使用 express-资源模块,轻松创建我的CRUD路由的API资源。但是有一些我不高兴的事情,并且认为我可以做得更好。



第一个是Mongoose。如果我想为我的API编写测试,我没有办法把Mongoose存入内存数据。所有的教程似乎都指向了Mongoose,但是我真的不知道我应该使用什么。



其次,我的资源似乎有一个很多样板代码。这是否真的是在Node.js中创建RESTful API的最佳方法?是否有其他模块可以帮助我创建我的CRUD路由?我相信有一些方法可以直接从您的架构创建CRUD路线,而不用再编码了,但我真的不知道如何。



我已经看到了这样的项目作为Tower.js和CompoundJS(正式的RailwayJS),似乎是这些全面的解决方案,比我在这里解决的更多。也许我应该使用它们,但是我真的只希望Node.js应用程序成为一个API,而不是其他的。我正在独立于API处理前端。



为了提供一些上下文,这里是我目前的情况。目前,我有一个在Mongoose中定义的模型:

  var mongoose = require('mongoose')
,Schema = mongoose.Schema
,Link

var LinkSchema = new Schema({
uri:String,
meta:{
title:String,
desc:String
},
share:[{
uid:Schema.Types.ObjectId,
date:Date,
message:String
} ]
})

Link = module.exports = mongoose.model('Link')

接下来,我定义了CRUD路由的控制器:

  var mongoose = require('mongoose ')
,_ = require('underscore')
,Link = mongoose.model('Link')

exports.load = function(req,id,fn) {
Link.findById(req.params.link,function(err,link){
if(err){
return res.send(err)
}

fn(null,link)
})
}

exports.index = function(req,res){
var filterByUs呃= req.query.user? {'shares.uid':req.query.user}:{}

Link.find(filterByUser,function(err,links){
if(err){
return res.send(err)
}

res.send(links)
})
}

exports.create = function (req,res){
var link = new Link(req.body)

link.save(function(err){
if(err){
// TODO:send 404
return res.send(err)
}

res.send(link)
})
}

exports.show = function(req,res){
res.send(req.link)
}

exports.update = function(req,res ){
req.link = _(req.link).extend(req.body)

req.link.save(function(err,link){
if(错误){
return res.send(err)
}

res.send(link)
})
}

exports.patch = exports.update

exports.destroy = function(req,res){
req.link.remove(function(err){
if(err ){
return res.send(er r)
}

res.send()
})
}

最后,我使用 express-resource 模块将这些控制器映射到Express应用程序之上必需的CRUD路由。 p>

  app.resource('api / links',require('../ resources / links')


解决方案

您应该查看重新设置



如果要使用express,还可以查看我所做的这个项目 - 节点休息



这个图书馆似乎更加成熟,拥有更多功能: https://github.com/jspears/mers


I'm a beginner in Node (and generally all back-end web development), and I have started to write a RESTful API in Node. There are a few things I'm trying to get my head around.

My application uses Express and Mongoose, and I am using the express-resource module to easily create my CRUD routes for the API resources. But there are a couple of things I am unhappy about, and think I could do better.

The first is Mongoose. If I want to write tests for my API, I have no way of stubbing Mongoose to force it to in memory data. All of the tutorials out there seem to point to Mongoose, however, and I'm really not sure what I should be using.

Secondly, my resource seems to have a lot of boilerplate code. Is this really the best way to create a RESTful API in Node.js? Are there other modules that will help me to create my CRUD routes? I believe there are ways you can create CRUD routes right from your schema, without anymore code, but I'm really not sure how.

I have seen projects out there such as Tower.js and CompoundJS (formally RailwayJS) that seem to be these comprehensive solutions that solve much more than my issues here. Perhaps I should be using them, but I really only want the Node.js application to be an API and nothing more. I am dealing with the front-end independently of the API.

To provide some context, here is my current situation. Currently, I have a model defined in Mongoose:

var mongoose = require('mongoose')
  , Schema = mongoose.Schema
  , Link

var LinkSchema = new Schema({
  uri: String,
  meta: {
    title: String,
    desc: String
  },
  shares: [{
    uid: Schema.Types.ObjectId,
    date: Date,
    message: String
  }]
})

Link = module.exports = mongoose.model('Link')

Next, I define the controllers for the CRUD routes:

var mongoose = require('mongoose')
  , _ = require('underscore')
  , Link = mongoose.model('Link')

exports.load = function (req, id, fn) {
  Link.findById(req.params.link, function (err, link) {
    if (err) {
      return res.send(err)
    }

    fn(null, link)
  })
}

exports.index = function (req, res) {
  var filterByUser = req.query.user ? { 'shares.uid': req.query.user } : {}

  Link.find(filterByUser, function (err, links) {
    if (err) {
      return res.send(err)
    }

    res.send(links)
  })
}

exports.create = function (req, res) {
  var link = new Link(req.body)

  link.save(function (err) {
    if (err) {
      // TODO: send 404
      return res.send(err)
    }

    res.send(link)
  })
}

exports.show = function (req, res) {
  res.send(req.link)
}

exports.update = function (req, res) {
  req.link = _(req.link).extend(req.body)

  req.link.save(function (err, link) {
    if (err) {
      return res.send(err)
    }

    res.send(link)
  })
}

exports.patch = exports.update

exports.destroy = function (req, res) {
  req.link.remove(function (err) {
    if (err) {
      return res.send(err)
    }

    res.send()
  })
}

Finally, I use the express-resource module to map these controllers to the necessary CRUD routes on top of the Express app.

app.resource('api/links', require('../resources/links'))

解决方案

You should look into restify

If you want to use express, you can also check out this project that I made -- called node-restful.

This library seems to be much more mature and have more features though: https://github.com/jspears/mers

这篇关于如何在Node.js中最好地创建RESTful API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆