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 all commits
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
42 changes: 42 additions & 0 deletions todos-mongokitten-openapi/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// 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/swift-server/swift-openapi-hummingbird.git", branch: "2.x.x"),
.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: "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)),
]
),
]
)
14 changes: 14 additions & 0 deletions todos-mongokitten-openapi/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Todos MongoKitten OpenAPI

This is an implementation of an API using an OpenAPI specification. The API uses a MongoDB database accessed via MongoKitten to store the todo data.

This API has four routes:

- GET /todos: Lists all the todos in the database
- POST /todos: Creates a new todo
- GET /todos/:id : Returns a single todo with id
- PUT /todos/:id : Overwrite properties of a todo with id

A todo consists of an array called `items`, containing the tasks that you still need to do.

This example comes with a [PAW](https://paw.cloud/) file you can use to test the various endpoints.
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
113 changes: 113 additions & 0 deletions todos-mongokitten-openapi/Sources/todos-mongokitten-openapi/API.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
@preconcurrency import MongoKitten
import OpenAPIRuntime
import TodosOpenAPI

/// The database model for a Todo
struct TodoModel: Codable {
/// The TodoModel's unique identifier
/// In MongoDB, `_id` is the primary key for a document
/// While MongoDB supports any type as the primary key,
/// `ObjectId` is the recommended type for primary keys
let _id: ObjectId

/// The checklist of items that are part of the Todo
var items: [String]
}

extension Components.Schemas.Todo {
/// Maps a `TodoModel` to a `Components.Schemas.Todo`
/// This makes it easier to send models to the API
init(model: TodoModel) {
self.init(id: model._id.hexString, items: model.items)
}
}

/// An implementation of the API protocol as specified in TodosOpenAPI/openapi.yaml
struct API: APIProtocol {
let mongo: MongoDatabase

/// The API route for creating a new Todo as specified TodosOpenAPI/openapi.yaml
func createTodo(
_ input: Operations.createTodo.Input
) async throws -> Operations.createTodo.Output {
// Extract the JSON body from the request
// Since the body of an OpenAPI request is an enum, we need to switch on it
let items = switch input.body {
case .json(let todo):
todo.items
}

// Create a new TodoModel, generating a new primary key
// And using the todo items from the request body
let model = TodoModel(_id: ObjectId(), items: items)

// Insert the model into the database.
// This method will encode the model to BSON, MongoDB's native format
try await mongo["todos"].insertEncoded(model)

// Return the model to the client as JSON
return .ok(.init(body: .json(.init(model: model))))
}

func getTodos(
_ input: Operations.getTodos.Input
) async throws -> Operations.getTodos.Output {
// Find all the TodoModels in the database
let models = try await mongo["todos"].find()
// Decode each entity from BSON to a TodoModel
.decode(TodoModel.self)
// Lazily map each TodoModel to a Components.Schemas.Todo
.map(transform: Components.Schemas.Todo.init)
// Drain the results into an array
.drain()

// Return the array of Components.Schemas.Todo to the client as JSON
return .ok(.init(body: .json(models)))
}

func getTodo(
_ input: Operations.getTodo.Input
) async throws -> Operations.getTodo.Output {
// Extract the id from the path, and attempt to convert it to an ObjectId
guard let id = ObjectId(input.path.id) else {
// If the id is not a valid ObjectId, return a 400 Bad Request
return .badRequest(.init(body: .json(.init(message: "Invalid id format"))))
}

// Find the TodoModel with the specified id
// The primary key (id) is stored in the `_id` field in MongoDB
// This call also decodes the BSON to a `TodoModel``
guard let model = try await mongo["todos"].findOne("_id" == id, as: TodoModel.self) else {
// If no TodoModel was found, return a 404 Not Found
return .notFound(.init())
}

// If it _was_ found, send the model to the client as JSON
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
}

// Create a new model, with the same id as the original
let model = TodoModel(_id: id, items: items)

// Update (overwrite) the model in the database
guard try await mongo["todos"].updateEncoded(where: "_id" == id, to: model).updatedCount == 1 else {
// If the model was not updated, return a 404 Not Found
// Since this means the _id does not exist in the database
return .notFound(.init())
}

return .ok(.init(body: .json(.init(model: model))))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
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

/// The MongoDB connection string to use to connect to the database
/// The following command can get you started with a local MongoDB instance:
///
/// docker run -d -p 27017:27017 mongo
@Option(name: .shortAndLong)
var connectionString: String = "mongodb://localhost:27017/mongo-todos"

func run() async throws {
// Connect to MongoDB
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