前端開發一般都是調用后端提供的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
在寫這個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)")
}
那么我們訪問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()