Commmunity-supported Swift Driver for FaunaDB

Overview

Commmunity-supported Swift Driver for FaunaDB

FaunaDB's Swift driver is now "community-supported". New features won't be exposed in the driver unless the necessary changes are contributed by a community member. Please email [email protected] if you have any questions/concerns, or would like to take a more active role in the development of the driver (eg. partnering with us and operating as a "maintainer" for the driver).

CocoaPods Coverage Status License

A Swift driver for FaunaDB

Supported Platforms

  • iOS 9.0+ | OSX 10.10+ | tvOS 9.0+ | watchOS 2.0+
  • Xcode 8
  • Swift 3

Documentation

Check out the Swift-specific reference documentation.

You can find more information in the FaunaDB documentation and in our example project.

Using the Driver

Installing

CocoaPods:

pod 'FaunaDB', '~> 2.0.0'

Carthage:

github 'fauna/faunadb-swift'

SwiftPM:

.Package(url: "https://github.com/fauna/faunadb-swift.git", Version(2, 0, 0))

Basic Usage

title, "body" => body ) } } extension Post: FaunaDB.Decodable { init?(value: Value) throws { try self.init( title: value.get("title") ?? "Untitled", body: value.get("body") ) } } let client = FaunaDB.Client(secret: "your-key-secret-here") // Creating a new post try! client.query( Create( at: Class("posts") Obj("data" => Post("My swift app", nil)) ) ).await(timeout: .now() + 5) // Retrieve a saved post let getPost = client.query(Get(Ref(class: Class("posts"), id: "42"))) let post: Post = try! getPost.map { dbEntry in dbEntry.get("data") } .await(timeout: .now() + 5)">
import FaunaDB

struct Post {
    let title: String
    let body: String?
}

extension Post: FaunaDB.Encodable {
    func encode() -> Expr {
        return Obj(
            "title" => title,
            "body" => body
        )
    }
}

extension Post: FaunaDB.Decodable {
    init?(value: Value) throws {
        try self.init(
            title: value.get("title") ?? "Untitled",
            body: value.get("body")
        )
    }
}

let client = FaunaDB.Client(secret: "your-key-secret-here")

// Creating a new post
try! client.query(
    Create(
        at: Class("posts")
        Obj("data" => Post("My swift app", nil))
    )
).await(timeout: .now() + 5)

// Retrieve a saved post
let getPost = client.query(Get(Ref(class: Class("posts"), id: "42")))
let post: Post = try! getPost.map { dbEntry in dbEntry.get("data") }
    .await(timeout: .now() + 5)

For more examples, check our online documentation and our example project.

Contributing

GitHub pull requests are very welcome.

Driver Development

You can compile and run the test with the following command:

FAUNA_ROOT_KEY=your-keys-secret-here swift test

LICENSE

Copyright 2018 Fauna, Inc.

Licensed under the Mozilla Public License, Version 2.0 (the "License"); you may not use this software except in compliance with the License. You may obtain a copy of the License at

http://mozilla.org/MPL/2.0/

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Comments
  • Reviewing swift driver syntax and DSL ergonomics

    Reviewing swift driver syntax and DSL ergonomics

    Closes: https://github.com/faunadb/sales-engineering/issues/413, https://github.com/faunadb/sales-engineering/issues/273

    Major changes:

    • Making sure our library doesn't add any method to native types
    • Implements the value tree hierarchy
    • Refactoring field extractors to make extensive usage of the type system
    • Improve error messages, specially for field extractors
    • Move from callbacks to future oriented api (with our own QueryResult type)
    • Review usage of named parameters
    • Increase test coverage
    • Adds lint

    Not included:

    • Support high precision timestamps. https://github.com/faunadb/sales-engineering/issues/414
    • API docs: https://github.com/faunadb/sales-engineering/issues/431
    opened by erickpintor 10
  • Implement FaunaDB Client.

    Implement FaunaDB Client.

    Ideally it should not depend on 3rd party dependencies. I think it should be written directly on top of NSURLSession (Foundation) and do not depend on any external networking library. Eventually https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSURLSession.swift will be implemented and this will allow us to run on linux.

    Key features:

    Configuration:

    • baseURL (includes scheme, domain and port).
    • requestTimeout.
    • observers support.
    • authToken
    • methods to perform queries...

    Am I missing something important? Any other critical feature for the client? @freels @erickpintor

    Client done 
    opened by mtnbarreto 8
  • Make the public DSL less dependent on knowledge about internal types

    Make the public DSL less dependent on knowledge about internal types

    I'm opening this issue so we can discuss how the internal types are being converted to Expr.

    Right now there are places where we need to write code like this:

    Create(ref: Ref.indexes, params: [
      "name": "spells_by_element",
      "source": Ref("classes/spells"),
      "terms": [["path": "data.element"] as Obj] as Arr, 
      "active": true
    ])
    

    [["path": "data.element"] as Obj] as Arr

    I think as Obj and as Arr requires previous knowledge about the internal Expr class hierarch and exposes that fact that we have internal representations of our own. Therefore, it loses the meaning of having literal conversions.

    Ideally, the user doesn't need to know about ArrayV, ObjectV or any other internal type. We should make them transparent to the user.

    In Java, we have functions to construct objects, arrays and internal values so the user doesn't need to construct them manually. The user only works with functions at the Expr level:

    Create(Ref("indexes"), Obj(
      "name", Value("spells_by_element"),
      "source", Ref("classes/spells"),
      "terms": Arr(Obj("path", Value("data.element"))), 
      "active": Value(true)
    )
    

    Since in Scala we have implicit conversions, the user needs to know even less about the internal types:

    Create(Ref("indexes"), Obj(
      "name" -> "spells_by_element",
      "source" -> Ref("classes/spells"),
      "terms" -> Arr(Obj("path", "data.element")), 
      "active" -> true
    )
    

    I believe that if we follow some ground rules we can make a Swift DSL a bit more fluid. What I would like to see is if we could provide a DSL similar to this:

    Create(ref: "indexes", [
      "name": "spells_by_element",
      "source": Ref("classes/spells"),
      "terms": [["path": "data.element"]], 
      "active": true
    )
    

    There rules for that syntax are:

    • Literals convert to Expr, not subtypes of Value. Perhaps, we don't need to make Value extends `Expr.
    • Parameters with type Expr are unnamed. Named parameters are used to infer types. For example Create(ref: "indexes") vs Create(Ref("indexes")).

    Those rules are very similar to the Scala implementation at the moment and seems to be the cleanest typed language we got so far.

    Let me know you're thoughts.

    done 
    opened by erickpintor 7
  • Result parsing is a bit verbose

    Result parsing is a bit verbose

    I think Result verbose and, most of the time, you're more interested on result value rather than knowing it there was an error or not.

    We could provide a general error handling that you attach to the client and a version of the query method that only call the call back if the query succeed.

    That would make the code more concise and less verbose.

    done 
    opened by erickpintor 7
  • added support for OSX, tvOS, watchOS

    added support for OSX, tvOS, watchOS

    closes #54. I also added the test for each platform. Source and test files are shared among platforms. Only required change was the set up of each dynamic framework and its associated tests.

    opened by mtnbarreto 5
  • Investigate support for Integer types

    Investigate support for Integer types

    At the moment we support Int as a Scalar type. I wonder what happens if the user wants to work with values bigger than a Int. In Java and Scala, the DLS works with Long type to guarantee compatibility with all possible number types.

    awaiting feedback 
    opened by erickpintor 5
  • Confirm if HTTP connection uses Keep-Alive

    Confirm if HTTP connection uses Keep-Alive

    To improve performance, FaunaDB allows http keep-alive connections. The should drivers issue requests with keep-alive header on.

    The idle timeout for http connections is 5 seconds on the server, we should set it to a bit less on the client. 4 seconds should be fine.

    awaiting feedback done 
    opened by erickpintor 5
  • Discarding results of map functions at QueryResult

    Discarding results of map functions at QueryResult

    Closes: https://github.com/faunadb/sales-engineering/issues/444

    It seems odd at first but, while developing the Example project I quickly realize that most of the time you're not interested on the actual result but rather to react upon it's completion.

    For example:

            Post.save(postToSave).map(at: .main) { [weak self] savedPost in
                self?.post = savedPost
                self?.goBackToPreviousView()
            }
    

    The alternative would be to call await, which blocks the thread preventing the user to cancel the action, if needed.

    opened by erickpintor 4
  • Client class enhancements

    Client class enhancements

    • [x] observers should be private

    query method:

    • [x] should always require the callback function
    • [x] should never submit an empty NSData
    • [x] ~~should not return NSURLSessionDataTask~~

    handleQueryErrors method:

    • [x] should not throw a NetworkException on cast error
    • [x] should not be responsible for parsing the response data
    • [x] should not call print
    done 
    opened by erickpintor 4
  • Setup repository and environment support

    Setup repository and environment support

    1. Base Xcode project.
    2. Dependency manager support. cocoapods and carthage for now.
    3. Unit tests target.
    4. Example App.
    5. Automated UI testing for Example app. (?)
    6. Travis .yml file.

    These tasks only includes environment support. Driver, testing, example app code are not included in this task.

    done 
    opened by mtnbarreto 4
  • Analysing code coverage reports

    Analysing code coverage reports

    • Ignoring tests folder
    • Testing AtomicInt overflow
    • Fix bug on equality operator for ValidationFailure

    The rest of the missing branches are either places where the coverage instrumentation can't verify that the branch was called but I manually check that they are being executed, safe guards for unexpected errors, or string representations for data structures.

    opened by erickpintor 3
Owner
Fauna, Inc.
Fauna is a flexible, developer-friendly, transactional database delivered as a secure, scalable, web-native API.
Fauna, Inc.
MySQL driver for Swift 3 (macOS and Linux)

MySQL MySQL Usage // do your magic Installation import PackageDescription let package = Package( dependencies: [ .Package(url: "https://g

Zewo Graveyard 29 Jan 29, 2022
The official MongoDB driver for Swift

MongoSwift The official MongoDB driver for Swift applications on macOS and Linux. Index Documentation Bugs/Feature Requests Installation Step 1: Insta

mongodb 317 Jan 8, 2023
SQLite.swift - A type-safe, Swift-language layer over SQLite3.

SQLite.swift provides compile-time confidence in SQL statement syntax and intent.

Stephen Celis 8.7k Jan 3, 2023
šŸ§” SQLiteOrm-Swift is an ORM library for SQLite3 built with Swift 5

?? Easy to use SQLite ORM library written with Swift

Yevgeniy Zakharov 25 Oct 6, 2022
ObjectBox Swift - persisting your Swift objects superfast and simple

ObjectBox Swift ObjectBox is a superfast, light-weight object persistence framework. This Swift API seamlessly persists objects on-device for iOS and

ObjectBox 380 Dec 19, 2022
Shows the issue with swift using an ObjC class which has a property from a swift package.

SwiftObjCSwiftTest Shows the issue with swift using an ObjC class which has a property from a swift package. The Swift class (created as @objc derived

Scott Little 0 Nov 8, 2021
Ios-App-ication-Swift - A simple iOS application made in Xcode using Swift

?? iPhone Calculator A simple iOS application made in Xcode using Swift. This ap

Kushal Shingote 1 Feb 2, 2022
Save-the-dot-project-swift - Save the dot project with swift

Save the Dot Apple introduced UIViewPropertyAnimator for iOS 10. We can use this

Kushal Shingote 2 Feb 8, 2022
The Swift Package Index is the place to find Swift packages!

The Swift Package Index helps you make better decisions about the dependencies you use in your apps. The Swift Package Index is a search engine for pa

Swift Package Index 389 Dec 22, 2022
A stand-alone Swift wrapper around the mongo-c client library, enabling access to MongoDB servers.

This package is deprecated in favour of the official Mongo Swift Driver. We advise users to switch to that pack

PerfectlySoft Inc. 54 Jul 9, 2022
Elegant library to manage the interactions between view and model in Swift

An assistant to manage the interactions between view and model ModelAssistant is a mediator between the view and model. This framework is tailored to

Seyed Samad Gholamzadeh 28 Jan 29, 2022
CRUD is an object-relational mapping (ORM) system for Swift 4+.

CRUD is an object-relational mapping (ORM) system for Swift 4+. CRUD takes Swift 4 Codable types and maps them to SQL database tables. CRUD can create tables based on Codable types and perform inserts and updates of objects in those tables. CRUD can also perform selects and joins of tables, all in a type-safe manner.

PerfectlySoft Inc. 61 Nov 18, 2022
CoreXLSX is a Excel spreadsheet (XLSX) format parser written in pure Swift

CoreXLSX Excel spreadsheet (XLSX) format parser written in pure Swift CoreXLSX is a library focused on representing the low-level structure of the XML

null 684 Dec 21, 2022
Solutions to LeetCode by Swift

LeetCode by Swift LeetCode Online Judge is a website containing many algorithm questions. Most of them are real interview questions of Google, Faceboo

Soap 4.5k Jan 5, 2023
Super lightweight DB written in Swift.

Use of value types is recommended and we define standard values, simple structured data, application state and etc. as struct or enum. Pencil makes us store these values more easily.

Naruki Chigira 88 Oct 22, 2022
YapDB is a collection/key/value store with a plugin architecture. It's built atop sqlite, for Swift & objective-c developers.

YapDatabase is a collection/key/value store and so much more. It's built atop sqlite, for Swift & Objective-C developers, targeting macOS, iOS, tvOS &

Yap Studios 3.3k Dec 29, 2022
CoreData/Realm sweet wrapper written in Swift

What is SugarRecord? SugarRecord is a persistence wrapper designed to make working with persistence solutions like CoreData in a much easier way. Than

Modo 2.1k Dec 9, 2022
Unrealm is an extension on RealmCocoa, which enables Swift native types to be saved in Realm.

Unrealm enables you to easily store Swift native Classes, Structs and Enums into Realm . Stop inheriting from Object! Go for Protocol-Oriented program

Artur  Mkrtchyan 518 Dec 13, 2022
Prephirences is a Swift library that provides useful protocols and convenience methods to manage application preferences, configurations and app-state. UserDefaults

Prephirences - PreĻ•rences Prephirences is a Swift library that provides useful protocols and convenience methods to manage application preferences, co

Eric Marchand 557 Nov 22, 2022