swift学习专题

用Swift写个简单的api

2016-12-26  本文已影响165人  TonyDuan

前端开发一般都是调用后端提供的json格式的数据,Perfect让我们可以用轻松的姿势来造一个api。

Server-side Swift. The Perfect library, application server, connectors and example apps. (For mobile back-end development, website and web app development, and more...) https://www.perfect.org

Perfect地址

在写这个demo前需要对有些知识有个初步的了解:

1.Swift Package Manager

import PackageDescription

let package = Package(
 name: "PerfectTemplate",
 targets: [],
 dependencies: [
  .Package(url: "https://github.com/PerfectlySoft/Perfect-HTTPServer.git", majorVersion: 2, minor: 0),
  .Package(url:"https://github.com/PerfectlySoft/Perfect-MongoDB.git", majorVersion: 2, minor: 0)

    ]
)

关键步骤总结:
①、添加package依赖后,在对应的目录运行

swift build

②、如果我们需要在Xcode中进行调试,执行

swift package generate-xcodeproj

③、对应还有swift build 的清除

swift build --clean

添加了新的依赖后,需要重新运行一次 ②,才会在Xcode看到新添加的库

2.URL路由

3.HTTPRequest & HTTPResponse

4.MongoDB & MongoDB 驱动

在我安装mongod的驱动中,用brew安装始终工作不起来,于是直接去github clone在本地编译Mongo c driver、安装,可能遇到的问题参考下面的办法解决。

https://jira.mongodb.org/browse/CDRIVER-941

Following its advice, this builds the C Driver:

$ make CPPFLAGS="-I/usr/local/opt/openssl/include" LDFLAGS="-L/usr/local/opt/openssl/lib"

Another approach is, after "brew install openssl", to do "brew link openssl --force", which installs headers to /usr/local/include/openssl.

$ brew install openssl

$ brew link openssl --force

假如以上几个步骤我们都了解了,并且在你本地环境中有安装MongoDB,或者你可以远程连接一个MongoDB数据库。

1.开启MongoDB数据服务,以便我们以Perfect的模板工程中调用

mongod 

2.为了方便我直接fork了Perfect的模板工程,在这个的基础上进行二次加工
https://github.com/PerfectlySoft/PerfectTemplate
还是来看下Hello,World,lol:

import PerfectLib
import PerfectHTTP
import PerfectHTTPServer

// 创建一个http的服务
let server = HTTPServer()

// 注册路由和句柄
var routes = Routes()
routes.add(method: .get, uri: "/", handler: {
        request, response in
        response.appendBody(string: "<html><title>Hello, world!</title><body>Hello, world!</body></html>")
        response.completed()
    }
)

// 给当前的服务添加路由
server.addRoutes(routes)

// 配置监听端口
server.serverPort = 8181

// Set a document root.
// This is optional. If you do not want to serve static content then do not set this.
// Setting the document root will automatically add a static file handler for the route /**
server.documentRoot = "./webroot"

// Gather command line options and further configure the server.
// Run the server with --help to see the list of supported arguments.
// Command line arguments will supplant any of the values set above.
configureServer(server)

do {
    // Launch the HTTP server.
    try server.start()
} catch PerfectError.networkError(let err, let msg) {
    print("Network error thrown: \(err) \(msg)")
}
Xcode工程 访问结果

那么我们访问MongoDB中的数据可以分解为

1.添加url路由

routes.add(method: .get,uri: "/mongo",handler: {})

2.以url中的参数来作为mongod的查询条件

   let queryBson = BSON()
    if let filterSeed = request.param(name: "name") {
        queryBson.append(key: "name", string: filterSeed)
    }

3.在Perfect-Mongod中的find用法

在Perfect的MongoDB封装中都是以传递BSON格式,同MongoDB中的find过滤find({},{key0:true/false,key1:true/false})不同

let fnd = collection.find(query: queryBson, fields: removefieldsName)

** query:就是用来查询条件 **
** fields:需要移除key,由于我看着_id表示别扭,所以将其移除 **

 let client = try! MongoClient(uri: "mongodb://localhost")
    // set database, assuming "test" exists
    let db = client.getDatabase(name: "test")
    

    // define collection
    guard let collection = db.getCollection(name: "test") else {
        return
    }
    // Here we clean up our connection,
    // by backing out in reverse order created
    defer {
        collection.close()
        db.close()
        client.close()
    }
    let queryBson = BSON()
    if let filterSeed = request.param(name: "name") {
        queryBson.append(key: "name", string: filterSeed)
    }
    let removefieldsName = BSON()
    removefieldsName.append(key: "_id")
//    filds.append(key: "age")
    // Perform a "find" on the perviously defined collection
    let fnd = collection.find(query: queryBson, fields: removefieldsName)
    
    // Initialize empty array to receive formatted results
    var arr = [String]()
    
    // The "fnd" cursor is typed as MongoCursor, which is iterable
    for x in fnd! {
        arr.append(x.asString)
    }
    
    // return a formatted JSON array.  
    let returning = "{\"data\":[\(arr.joined(separator: ","))]}"
    
    // Return the JSON string
    response.appendBody(string: returning)
    response.completed()
没有传递参数,只是匹配路由查询所有数据 请求中传入参数:duanhai 😝
上一篇下一篇

猜你喜欢

热点阅读