Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2.x.x mongokitten tutorial #51

Merged
merged 4 commits into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions todos-mongokitten-openapi/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.DS_Store
/.build
/Packages
xcuserdata/
DerivedData/
.swiftpm/configuration/registries.json
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
.netrc
43 changes: 43 additions & 0 deletions todos-mongokitten-openapi/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// swift-tools-version: 5.9
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "todos-mongokitten-openapi",
platforms: [ .macOS(.v14) ],
dependencies: [
.package(url: "https://github.com/hummingbird-project/hummingbird.git", branch: "2.x.x"),
.package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.0.0"),
.package(url: "https://github.com/orlandos-nl/mongokitten.git", from: "7.0.0"),
.package(url: "https://github.com/Joannis/swift-openapi-hummingbird.git", branch: "feature/jo/support-hb-2.x.x"),
Joannis marked this conversation as resolved.
Show resolved Hide resolved
.package(url: "https://github.com/apple/swift-openapi-generator.git", from: "1.2.0"),
.package(url: "https://github.com/apple/swift-openapi-runtime.git", from: "1.3.0"),
],
targets: [
.target(
name: "TodosOpenAPI",
dependencies: [
.product(name: "OpenAPIRuntime", package: "swift-openapi-runtime"),
],
plugins: [.plugin(name: "OpenAPIGenerator", package: "swift-openapi-generator")]
),
.executableTarget(
name: "todos-mongokitten-openapi",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
.product(name: "Hummingbird", package: "hummingbird"),
.product(name: "HummingbirdFoundation", package: "hummingbird"),
Joannis marked this conversation as resolved.
Show resolved Hide resolved
.product(name: "MongoKitten", package: "mongokitten"),
.product(name: "OpenAPIHummingbird", package: "swift-openapi-hummingbird"),
.target(name: "TodosOpenAPI"),
],
swiftSettings: [
// Enable better optimizations when building in Release configuration. Despite the use of
// the `.unsafeFlags` construct required by SwiftPM, this flag is recommended for Release
// builds. See <https://github.com/swift-server/guides#building-for-production> for details.
.unsafeFlags(["-cross-module-optimization"], .when(configuration: .release)),
]
),
]
)
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
generate:
- types
- server
accessModifier: package
128 changes: 128 additions & 0 deletions todos-mongokitten-openapi/Sources/TodosOpenAPI/openapi.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
openapi: '3.1.0'
Joannis marked this conversation as resolved.
Show resolved Hide resolved
info:
title: GreetingService
version: 1.0.0
servers:
- url: http://localhost:8080
description: Local
paths:
/todos:
post:
operationId: createTodo
requestBody:
description: A todo to create.
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/TodoContents'
responses:
'200':
description: A success response with the created todo.
content:
application/json:
schema:
$ref: '#/components/schemas/Todo'
get:
operationId: getTodos
responses:
'200':
description: A success response with a list of todos.
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Todo'
/todos/{id}:
get:
operationId: getTodo
parameters:
- $ref: '#/components/parameters/TodoId'
responses:
'200':
description: A success response with a todo.
content:
application/json:
schema:
$ref: '#/components/schemas/Todo'
'400':
description: A bad request response.
content:
application/json:
schema:
type: object
properties:
message:
type: string
description: A message describing the error.
'404':
description: This todo does not exist
put:
operationId: updateTodo
parameters:
- $ref: '#/components/parameters/TodoId'
requestBody:
description: The todo's new values.
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/TodoContents'
responses:
'200':
description: A success response with the updated todo.
content:
application/json:
schema:
$ref: '#/components/schemas/Todo'
'400':
description: A bad request response.
content:
application/json:
schema:
type: object
properties:
message:
type: string
description: A message describing the error.
'404':
description: This todo does not exist
components:
parameters:
TodoId:
name: id
in: path
description: The id of the Todo.
required: true
schema:
type: string
schemas:
TodoContents:
type: object
description: A value with the todo contents.
properties:
items:
type: array
description: A list of todo items.
items:
type: string
description: A string containing the todo item contents.
required:
- items
Todo:
type: object
description: A value with the todo contents.
properties:
id:
type: string
description: The id of the todo.
items:
type: array
description: A list of todo items.
items:
type: string
description: A string containing the todo item contents.
required:
- id
- items
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
@preconcurrency import MongoKitten
import OpenAPIRuntime
import TodosOpenAPI

struct TodoModel: Codable {
let _id: ObjectId
let items: [String]
Joannis marked this conversation as resolved.
Show resolved Hide resolved
}

extension Components.Schemas.Todo {
init(model: TodoModel) {
self.init(id: model._id.hexString, items: model.items)
}
}

struct API: APIProtocol {
let mongo: MongoDatabase

func createTodo(
_ input: Operations.createTodo.Input
) async throws -> Operations.createTodo.Output {
let items = switch input.body {
case .json(let todo):
todo.items
}

let model = TodoModel(_id: ObjectId(), items: items)
try await mongo["todos"].insertEncoded(model)
return .ok(.init(body: .json(.init(model: model))))
}

func getTodos(
_ input: Operations.getTodos.Input
) async throws -> Operations.getTodos.Output {
let models = try await mongo["todos"]
.find()
.decode(TodoModel.self)
.map(transform: Components.Schemas.Todo.init)
.drain()

return .ok(.init(body: .json(models)))
}

func getTodo(
_ input: Operations.getTodo.Input
) async throws -> Operations.getTodo.Output {
guard let id = ObjectId(input.path.id) else {
return .badRequest(.init(body: .json(.init(message: "Invalid id format"))))
}

guard let model = try await mongo["todos"].findOne("_id" == id, as: TodoModel.self) else {
return .notFound(.init())
}

return .ok(.init(body: .json(.init(model: model))))
}

func updateTodo(
_ input: Operations.updateTodo.Input
) async throws -> Operations.updateTodo.Output {
guard let id = ObjectId(input.path.id) else {
return .badRequest(.init(body: .json(.init(message: "Invalid id format"))))
}

let items = switch input.body {
case .json(let todo):
todo.items
}

let model = TodoModel(_id: id, items: items)
guard try await mongo["todos"].updateEncoded(where: "_id" == id, to: model).updatedCount == 1 else {
return .notFound(.init())
}

return .ok(.init(body: .json(.init(model: model))))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import ArgumentParser
import Hummingbird
import OpenAPIHummingbird
import OpenAPIRuntime
import MongoKitten

@main struct HummingbirdArguments: AsyncParsableCommand {
@Option(name: .shortAndLong)
var hostname: String = "127.0.0.1"

@Option(name: .shortAndLong)
var port: Int = 8080

@Option(name: .shortAndLong)
var connectionString: String = "mongodb://localhost:27017/mongo-todos"

func run() async throws {
let mongo = try await MongoDatabase.connect(to: connectionString)
let router = HBRouter()
router.middlewares.add(HBLogRequestsMiddleware(.info))
let api = API(mongo: mongo)
try api.registerHandlers(on: router)

let app = HBApplication(
router: router,
configuration: .init(address: .hostname(hostname, port: port))
)
try await app.runService()
}
}
Binary file added todos-mongokitten-openapi/api.paw
Binary file not shown.
Loading