簡體   English   中英

如何在Meteor中創建Rest API

[英]how to create a Rest API in Meteor

如何使用meteor設計/編寫高效的rest API,移動應用程序也可以使用它? 移動應用程序是否也可以利用流星反應式編程?

由於目前有如此多的編程選擇,重復不同平台的所有內容(代碼,api)似乎是浪費,而不是擁有一個很好的實用解決方案。

你的帖子真的是兩個不同的問題。

  1. 是的,有一種方法可以將REST端點連接到Meteor。 您只需使用connect或Express將它們編寫為普通的Node.js代碼,並在WebApp.connectHandlers webapp包( meteor add webapp )后將它們附加到WebApp.connectHandlers

  2. 移動應用程序可以通過在Javascript中實現來利用反應性。 您可以直接從移動瀏覽器訪問您的應用程序,也可以使用PhoneGap / Cordova將其包裝在“原生”應用程序容器中。 隨着手機變得越來越流行,這可能是部署應用程序的默認方式,而不是在不同的代碼庫中編寫同一應用程序的許多副本。

為了回答你的第一個問題,我發布了一個用於在Meteor 0.9+中編寫REST API的軟件包。 移動應用程序當然可以使用API​​:

https://github.com/krose72205/meteor-restivus

它受到RestStop2的啟發,並使用Iron Router的服務器端路由構建。

更新:我只想為找到這個的人提供一個代碼示例。 這是GitHub自述文件中的Restivus Quick Start示例:

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 2014年8月 ,它是現場演示的Meteor功能演示。

確實,您永遠不會接近Native應用程序的原始性能,但開發人員對您的項目所需的維護成本和技能組合也無法比擬。

對於API部分,可以使用Meteor生成RESTful API。 使用鐵路由器切換路由是一種可能的選擇。

發現流星書完整版有一個專門用於此的額外章節

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM