Add examples (#78)

* Add tiny example

* fix basic exmaple

* Add server/client exmaples

Co-authored-by: Emil Ivanichkov <emil.ivanichkov@gmail.com>

---------

Co-authored-by: Emil Ivanichkov <emil.ivanichkov@gmail.com>
This commit is contained in:
Shuu 2024-03-12 00:16:07 +09:00 committed by GitHub
parent 223aadeb82
commit a9687dda1c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 47 additions and 0 deletions

17
examples/basic.nim Normal file
View File

@ -0,0 +1,17 @@
import pkg/presto/[route, server]
proc decodeString*(t: typedesc[string], value: string): RestResult[string] =
ok(value)
proc validate(pattern: string, value: string): int = 0
when isMainModule:
var router = RestRouter.init(validate)
router.api(MethodGet, "/") do () -> RestApiResponse:
RestApiResponse.response("Hello World", Http200, "textt/plain")
let restServer = RestServerRef.new(router, initTAddress("127.0.0.1:9000")).get
restServer.start()
runForever()

12
examples/client.nim Normal file
View File

@ -0,0 +1,12 @@
import pkg/presto/[route, client]
import ../tests/helpers
proc hello() {.async.} =
var restClient = RestClientRef.new(initTAddress("127.0.0.1:9000"))
proc helloCall(body: string): string {.
rest, endpoint: "/hello/world", meth: MethodPost.}
let res = await restClient.helloCall("Hello Server!", restContentType = "text/plain")
echo "Server response: ", res
when isMainModule:
waitFor hello()

18
examples/server.nim Normal file
View File

@ -0,0 +1,18 @@
import pkg/presto/[route, server]
import stew/byteutils
proc validate(pattern: string, value: string): int = 0
when isMainModule:
var router = RestRouter.init(validate)
router.api(MethodPost, "/hello/world") do (
contentBody: Option[ContentBody]) -> RestApiResponse:
echo "Client says: ", string.fromBytes(contentBody.get().data)
RestApiResponse.response("Hello Client, I am Server", Http200, "textt/plain")
let restServer = RestServerRef.new(router, initTAddress("127.0.0.1:9000")).get
restServer.start()
runForever()