Swiftpack.co - netreconlab/parse-server-swift as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by netreconlab.
netreconlab/parse-server-swift 0.2.0
Write Server-Side Parse Cloud Code in Swift!
⭐️ 4
🕓 6 days ago
iOS macOS watchOS tvOS macCatalyst linux macOS iOS
.package(url: "https://github.com/netreconlab/parse-server-swift.git", from: "0.2.0")

ParseServerSwift

Documentation Tuturiol Build Status CI release codecov License


Write Parse Cloud Code in Swift!

What is Cloud Code? For complex apps, sometimes you just need logic that isn’t running on a mobile device. Cloud Code makes this possible. Cloud Code in ParseServerSwift is easy to use because it’s built using Parse-SwiftOG and Vapor. ParseServerSwift provides many additional benefits over the traditional JS based Cloud Code that runs on the Node.js parse-server:

Technically, complete apps can be written with ParseServerSwift, the only difference is that this code runs in your ParseServerSwift rather than running on the user’s mobile device. When you update your Cloud Code, it becomes available to all mobile environments instantly. You don’t have to wait for a new release of your application. This lets you change app behavior on the fly and add new features faster.

Creating Your Cloud Code App with ParseServerSwift

Setup a Vapor project by following the directions for installing and setting up your project on macOS or linux.

Then add ParseServerSwift to dependencies in your Package.swift file:

// swift-tools-version:5.5.2
import PackageDescription

let package = Package(
    name: "YOUR_PROJECT_NAME",
    dependencies: [
        .package(url: "https://github.com/netreconlab/ParseServerSwift", .upToNextMajor(from: "0.2.0")),
    ]
    ...
    targets: [
        .target(
            name: "YOUR_PROJECT_NAME",
            dependencies: [
                .product(name: "ParseServerSwift", package: "ParseServerSwift"),
            ]
        ),
    ]
)

Adding ParseServerSwift will allow you to quickly add routes for Parse Cloud Hook Functions and Triggers.

Configure ParseServerSwift to Connect to Your Parse Servers

Environment Variables

The following enviroment variables are available and can be configured directly or through .env, .env.production, etc. See the Vapor Docs for more details.

PARSE_SERVER_SWIFT_HOST_NAME: cloud-code # The name of your host. If you are running in Docker it should be same name as the docker service
PARSE_SERVER_SWIFT_PORT: # This is the default port on the docker image
PARSE_SERVER_SWIFT_DEFAULT_MAX_BODY_SIZE: 500kb # Set the default size for bodies that are collected into memory before calling your handlers (See Vapor docs for more details)
PARSE_SERVER_SWIFT_URLS: http://parse:1337/parse # (Required) Specify one of your Parse Servers to connect to. Can connect to multiple by seperating URLs with commas
PARSE_SERVER_SWIFT_APPLICATION_ID: appId # (Required) The application id of your Parse Server
PARSE_SERVER_SWIFT_PRIMARY_KEY: primaryKey # (Required) The master key of your Parse Server 
PARSE_SERVER_SWIFT_WEBHOOK_KEY: webookKey # The webhookKey of your Parse Server

WebhookKey

The webhookKey should match the webhookKey on the Parse Server.

Parse-SwiftOG SDK

The aforementioned environment variables automatically configure Parse-SwiftOG SDK. If you need a more custom configuration, see the documentation.

Initializing ParseSwiftServer

To levergage the aforementioned environment variables, you should modify configure.swift in your project to look similar to below:

public func configure(_ app: Application) throws {
    // Initialize ParseServerSwift
    let configuration = try ParseServerConfiguration(app: app)
    try ParseServerSwift.initialize(configuration, app: app)
    
    // register routes
    try routes(app)
}

If you want to pass the configuration parameters programitically, your configure method should look similar to below:

public func configure(_ app: Application) throws {
    // Initialize ParseServerSwift
    let configuration = try ParseServerConfiguration(app: app,
                                                     hostName: "hostName",
                                                     port: 8081,
                                                     applicationId: "applicationId",
                                                     primaryKey: "primaryKey",
                                                     webhookKey: hookKey,
                                                     parseServerURLString: "primaryKey")
    try ParseServerSwift.initialize(configuration, app: app)
    
    // register routes
    try routes(app)
}

Starting the Server

ParseServerSwift is optimized to run in Docker containers. A sample [docker-compose.yml] demonstrates how to quickly spin up one (1) ParseServerSwift server with one (1) parse-hipaa servers and (1) hipaa-postgres database.

In Docker

ParseSwift depends on FoundationNetworking when not built on Apple Platforms. Be sure to add the following lines to your Dockerfile release stage when building your own projects with ParseServerSwift.

  1. Fork this repo
  2. In your terminal, change directories into ParseServerSwift folder
  3. Type docker-compose up
  4. Accessing your containers:
image

On macOS

To start your server type, swift run in the terminal of the project root directory.

Writing Cloud Code

Creating ParseObject's

It is recommended to add all of your ParseObject's in a folder called Models similar to ParseServerSwift/Sources/ParseServerSwift/Models.

The ParseUser Model

Be mindful that the ParseUser in ParseServerSwift should conform to ParseCloudUser. This is because the ParseCloudUser contains some additional properties on the server-side. On the client, you should always use ParseUser instead of ParseCloudUser. In addition, make sure to add all of the additional properties you have in your _User class to the User model. An example User model is below:

/**
 An example `ParseUser`. You will want to add custom
 properties to reflect the `ParseUser` on your Parse Server.
 */
struct User: ParseCloudUser {

    var authData: [String: [String: String]?]?
    var username: String?
    var email: String?
    var emailVerified: Bool?
    var password: String?
    var objectId: String?
    var createdAt: Date?
    var updatedAt: Date?
    var ACL: ParseACL?
    var originalData: Data?
    var sessionToken: String?
    var _failed_login_count: Int?
    var _account_lockout_expires_at: Date?
}

An example ParseObject Model

The GameScore model is below:

import Foundation
import ParseSwift

/**
 An example `ParseObject`. This is for testing. You can
 remove when creating your application.
 */
struct GameScore: ParseObject {
    // These are required by ParseObject.
    var objectId: String?
    var createdAt: Date?
    var updatedAt: Date?
    var ACL: ParseACL?
    var originalData: Data?

    // Your own properties.
    var points: Int?

    // Implement your own version of merge.
    func merge(with object: Self) throws -> Self {
        var updated = try mergeParse(with: object)
        if updated.shouldRestoreKey(\.points,
                                     original: object) {
            updated.points = object.points
        }
        return updated
    }
}

Creating New Cloud Code Routes

Adding routes for ParseHooks are as simple as adding routes in Vapor. ParseServerSwift provides some additional methods to routes to easily create and register Hook Functions and Hook Triggers. All routes should be added to the routes.swift file in your project. Example ParseServerSwift routes can be found in ParseServerSwift/Sources/ParseServerSwift/routes.swift.

Be sure to add import ParseSwift and import ParseServerSwift to the top of routes.swift

Sending Errors From Cloud Code Routes

There will be times you will need to respond by sending an error to the Node.js Parse Server to propagate to the client. Sending errors can be accomplished by sending a ParseHookResponse. Below are two examples of sending an error:

// Note: `T` is the type to be returned if there is no error thrown.

// Standard Parse error with your own unique message
let standardError = ParseError(code: .missingObjectId, message: "This object requires an objectId")
return ParseHookResponse<T>(error: standardError) // Be sure to "return" the ParseHookResponse in your route, DO NOT "throw" the error.

// Custom error with your own unique code and message
let customError = ParseError(otherCode: 1001, message: "My custom error")
return ParseHookResponse<T>(error: customError) // Be sure to "return" ParseHookResponse in your route, DO NOT "throw" the error.

Cloud Code Examples

Parse-Swift has number of Swift Playgrounds to demonstrate how to use the SDK. Below are some notable Playgrounds specifically for Cloud Code that can be used directly in ParseServerSwift:

Cloud Code Functions

Cloud Code Functions can also take parameters. It's recommended to place all parameters in ParseServerSwift/Sources/ParseServerSwift/Models/Parameters

// A Parse Hook Function route.
app.post("hello",
         name: "hello") { req async throws -> ParseHookResponse<String> in
    // Note that `ParseHookResponse<String>` means a "successfull"
    // response will return a "String" type.
    if let error: ParseHookResponse<String> = checkHeaders(req) {
        return error
    }
    var parseRequest = try req.content
        .decode(ParseHookFunctionRequest<User, FooParameters>.self)
    
    // If a User called the request, fetch the complete user.
    if parseRequest.user != nil {
        parseRequest = try await parseRequest.hydrateUser(request: req)
    }
    
    // To query using the User's credentials who called this function,
    // use the options() method from the parseRequest
    let options = try parseRequest.options(req)
    let scores = try await GameScore.query.findAll(options: options)
    req.logger.info("Scores this user can access: \(scores)")
    return ParseHookResponse(success: "Hello world!")
}

Cloud Code Triggers

// A Parse Hook Trigger route.
app.post("score", "save", "before",
         className: GameScore.className,
         triggerName: .beforeSave) { req async throws -> ParseHookResponse<GameScore> in
    // Note that `ParseHookResponse<GameScore>` means a "successfull"
    // response will return a "GameScore" type.
    if let error: ParseHookResponse<GameScore> = checkHeaders(req) {
        return error
    }
    var parseRequest = try req.content
        .decode(ParseHookTriggerObjectRequest<User, GameScore>.self)

    // If a User called the request, fetch the complete user.
    if parseRequest.user != nil {
        parseRequest = try await parseRequest.hydrateUser(request: req)
    }

    guard let object = parseRequest.object else {
        return ParseHookResponse(error: .init(code: .missingObjectId,
                                              message: "Object not sent in request."))
    }
    // To query using the primaryKey pass the `usePrimaryKey` option
    // to ther query.
    let scores = try await GameScore.query.findAll(options: [.usePrimaryKey])
    req.logger.info("Before save is being made. Showing all scores before saving new ones: \(scores)")
    return ParseHookResponse(success: object)
}

// Another Parse Hook Trigger route.
app.post("score", "find", "before",
         className: GameScore.className,
         triggerName: .beforeFind) { req async throws -> ParseHookResponse<[GameScore]> in
    // Note that `ParseHookResponse<[GameScore]>` means a "successfull"
    // response will return a "[GameScore]" type.
    if let error: ParseHookResponse<[GameScore]> = checkHeaders(req) {
        return error
    }
    let parseRequest = try req.content
        .decode(ParseHookTriggerObjectRequest<User, GameScore>.self)
    req.logger.info("A query is being made: \(parseRequest)")

    // Return two custom scores instead.
    let score1 = GameScore(objectId: "yolo",
                           createdAt: Date(),
                           points: 50)
    let score2 = GameScore(objectId: "nolo",
                           createdAt: Date(),
                           points: 60)
    req.logger.info("""
        Returning custom objects to the user from Cloud Code instead of querying:
        \(score1); \(score2)
    """)
    return ParseHookResponse(success: [score1, score2])
}

// Another Parse Hook Trigger route.
app.post("user", "login", "after",
         className: User.className,
         triggerName: .afterLogin) { req async throws -> ParseHookResponse<Bool> in
    // Note that `ParseHookResponse<Bool>` means a "successfull"
    // response will return a "Bool" type. Bool is the standard response with
    // a "true" response meaning everything is okay or continue.
    if let error: ParseHookResponse<Bool> = checkHeaders(req) {
        return error
    }
    let parseRequest = try req.content
        .decode(ParseHookTriggerObjectRequest<User, GameScore>.self)

    req.logger.info("A user has logged in: \(parseRequest)")
    return ParseHookResponse(success: true)
}

// A Parse Hook Trigger route for `ParseFile`.
app.on("file", "save", "before",
       triggerName: .beforeSave) { req async throws -> ParseHookResponse<Bool> in
    // Note that `ParseHookResponse<Bool>` means a "successfull"
    // response will return a "Bool" type. Bool is the standard response with
    // a "true" response meaning everything is okay or continue. Sending "false"
    // in this case will reject saving the file.
    if let error: ParseHookResponse<Bool> = checkHeaders(req) {
        return error
    }
    let parseRequest = try req.content
        .decode(ParseHookTriggerRequest<User>.self)

    req.logger.info("A ParseFile is being saved: \(parseRequest)")
    return ParseHookResponse(success: true)
}

// Another Parse Hook Trigger route for `ParseFile`.
app.post("file", "delete", "before",
         triggerName: .beforeDelete) { req async throws -> ParseHookResponse<Bool> in
    // Note that `ParseHookResponse<Bool>` means a "successfull"
    // response will return a "Bool" type. Bool is the standard response with
    // a "true" response meaning everything is okay or continue.
    if let error: ParseHookResponse<Bool> = checkHeaders(req) {
        return error
    }
    let parseRequest = try req.content
        .decode(ParseHookTriggerRequest<User>.self)

    req.logger.info("A ParseFile is being deleted: \(parseRequest)")
    return ParseHookResponse(success: true)
}

// A Parse Hook Trigger route for `ParseLiveQuery`.
app.post("connect", "before",
         triggerName: .beforeConnect) { req async throws -> ParseHookResponse<Bool> in
    // Note that `ParseHookResponse<Bool>` means a "successfull"
    // response will return a "Bool" type. Bool is the standard response with
    // a "true" response meaning everything is okay or continue.
    if let error: ParseHookResponse<Bool> = checkHeaders(req) {
        return error
    }
    let parseRequest = try req.content
        .decode(ParseHookTriggerRequest<User>.self)

    req.logger.info("A LiveQuery connection is being made: \(parseRequest)")
    return ParseHookResponse(success: true)
}

// Another Parse Hook Trigger route for `ParseLiveQuery`.
app.post("score", "subscribe", "before",
         className: GameScore.className,
         triggerName: .beforeSubscribe) { req async throws -> ParseHookResponse<Bool> in
    // Note that `ParseHookResponse<Bool>` means a "successfull"
    // response will return a "Bool" type. Bool is the standard response with
    // a "true" response meaning everything is okay or continue.
    if let error: ParseHookResponse<Bool> = checkHeaders(req) {
        return error
    }
    let parseRequest = try req.content
        .decode(ParseHookTriggerObjectRequest<User, GameScore>.self)

    req.logger.info("A LiveQuery subscription is being made: \(parseRequest)")
    return ParseHookResponse(success: true)
}

// Another Parse Hook Trigger route for `ParseLiveQuery`.
app.post("score", "event", "after",
         className: GameScore.className,
         triggerName: .afterEvent) { req async throws -> ParseHookResponse<Bool> in
    // Note that `ParseHookResponse<Bool>` means a "successfull"
    // response will return a "Bool" type. Bool is the standard response with
    // a "true" response meaning everything is okay or continue.
    if let error: ParseHookResponse<Bool> = checkHeaders(req) {
        return error
    }
    let parseRequest = try req.content
        .decode(ParseHookTriggerObjectRequest<User, GameScore>.self)

    req.logger.info("A LiveQuery event occured: \(parseRequest)")
    return ParseHookResponse(success: true)
}

GitHub

link
Stars: 4
Last commit: 13 hours ago
jonrohan Something's broken? Yell at me @ptrpavlik. Praise and feedback (and money) is also welcome.

Release Notes

0.2.0
6 days ago

What's Changed

Full Changelog: https://github.com/netreconlab/parse-server-swift/compare/0.1.2...0.2.0

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics