Last active
June 6, 2018 22:17
-
-
Save neoneye/993bc16e583bff3dc4ae18284b2ce45a to your computer and use it in GitHub Desktop.
self documenting api using Perfect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import PerfectHTTP | |
class HandlerContext { | |
let request: HTTPRequest | |
let response: HTTPResponse | |
init(request: HTTPRequest, response: HTTPResponse) { | |
self.request = request | |
self.response = response | |
} | |
} | |
protocol Endpoint: class { | |
init() | |
var purpose: String { get } | |
func handler(context: HandlerContext) throws | |
} | |
class EP_GetDataList: Endpoint { | |
required init() {} | |
let purpose = "List files for a user" | |
func handler(context: HandlerContext) throws { | |
let userId = try context.request.userId() | |
guard let jsonString = context.request.param(name: "json") else { | |
throw NetworkError.custom("A 'json' parameter must be provided", .badRequest) | |
} | |
let json = JSON.parse(string: jsonString) | |
// ... impl ... | |
} | |
} | |
func installRoutes() { | |
scope("/v1") { | |
post("/data/upload", EP_PostDataUpload.self) | |
get ("/data/list", EP_GetDataList.self) | |
get ("/data/download",EP_GetDataDownload.self) | |
get ("/data/preview", EP_GetDataPreview.self) | |
get ("/type/list", EP_GetTypeList.self) | |
} | |
} | |
// Generated documentation looks like this: | |
// | |
// POST /v1/data/upload class: EP_PostDataUpload purpose: "Upload a file to a user" policy: secure | |
// GET /v1/data/list class: EP_GetDataList purpose: "List files for a user" policy: secure | |
// GET /v1/data/download class: EP_GetDataDownload purpose: "Download a file from a user" policy: secure |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment