【发布时间】:2014-09-06 11:19:53
【问题描述】:
如何使用meteor设计/编写一个高效的rest API,它也可以被移动应用程序使用?移动应用程序也可以利用流星反应式编程吗?
目前有这么多编程选择,为不同平台重复所有内容(代码、api)似乎很浪费,而不是有一个好的实用解决方案。
【问题讨论】:
如何使用meteor设计/编写一个高效的rest API,它也可以被移动应用程序使用?移动应用程序也可以利用流星反应式编程吗?
目前有这么多编程选择,为不同平台重复所有内容(代码、api)似乎很浪费,而不是有一个好的实用解决方案。
【问题讨论】:
您的帖子实际上是两个不同的问题。
是的,有一种方法可以将 REST 端点连接到 Meteor。您只需使用 connect 或 Express 将它们编写为普通 Node.js 代码,并在拉入 webapp 包 (meteor add webapp) 后将它们附加到 WebApp.connectHandlers。
移动应用程序可以通过在 Javascript 中实现来利用反应性。您可以直接从移动浏览器访问您的应用程序,或者仅使用 PhoneGap/Cordova 将其包装在“本机”应用程序容器中。随着手机变得越来越流行,这可能是部署应用的默认方式,而不是在不同的代码库中编写同一应用的多个副本。
【讨论】:
为了回答您的第一个问题,我发布了一个用于在 Meteor 0.9+ 中编写 REST API 的包。移动应用程序当然可以使用这些 API:
https://github.com/krose72205/meteor-restivus
它的灵感来自RestStop2,并使用Iron Router 的服务器端路由构建。
更新:我只是想为找到此内容的任何人提供一个代码示例。这是来自 GitHub README 的 Restivus 快速入门示例:
Items = new Mongo.Collection 'items'
if Meteor.isServer
# Global API configuration
Restivus.configure
useAuth: true
prettyJson: true
# Generates: GET, POST, DELETE on /api/items and GET, PUT, DELETE on
# /api/items/:id for Items collection
Restivus.addCollection Items
# Generates: GET, POST on /api/users and GET, DELETE /api/users/:id for
# Meteor.users collection
Restivus.addCollection Meteor.users,
excludedEndpoints: ['deleteAll', 'put']
routeOptions:
authRequired: true
endpoints:
post:
authRequired: false
delete:
roleRequired: 'admin'
# Maps to: /api/posts/:id
Restivus.addRoute 'posts/:id', authRequired: true,
get: ->
post = Posts.findOne @urlParams.id
if post
status: 'success', data: post
else
statusCode: 404
body: status: 'fail', message: 'Post not found'
post:
roleRequired: ['author', 'admin']
action: ->
post = Posts.findOne @urlParams.id
if post
status: "success", data: post
else
statusCode: 400
body: status: "fail", message: "Unable to add post"
delete:
roleRequired: 'admin'
action: ->
if Posts.remove @urlParams.id
status: "success", data: message: "Item removed"
else
statusCode: 404
body: status: "fail", message: "Item not found"
【讨论】:
要回答您问题的移动部分,
Meteor 将集成一个打包过程,通过使用 Cordova 将您的应用发布为 iOS / Android 应用。你可能想看看这个视频:Meteor Devshop SF August 2014,这是一个带有现场演示的 Meteor 功能演示。
确实,您永远无法接近 Native 应用程序的原始性能,但您的项目开发人员所需的维护成本和技能集也远非可比性。
对于 API 部分,可以使用 Meteor 生成 RESTful API。使用iron-router severside routing 是一种可能的选择。
Discover Meteor Book 的完整版有一个额外的章节专门用于此。
【讨论】: