Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Vapor Firebase Realtime database provider

License

NotificationsYou must be signed in to change notification settings

vapor-community/ferno

Repository files navigation

Ferno 🔥

Ferno allows you to easily connect your Vapor project with your Firebase realtime database. It is built with the brand new Vapor 4. It gives you a nice and clean interface to interact with the Firebase Realtime REST API. It will automatically turn the response into your class/struct!

Prerequisites

You will need:

  • Vapor 4.8+

Installing

In your Package.swift file, add the line

.package(url:"https://github.com/vapor-community/ferno.git", from:"0.6.0")

Also make sure you addFerno as a dependency

dependencies:[.product(name:"Ferno",package:"ferno")]

Setup

Legacy setup

  1. Ferno uses an access token to read and write to your database. First we will need to get your service account information.

    • Log into the Firebase console
    • Click the settings gear next toProject Overview
    • SelectProject settings
    • Select theSERVICE ACCOUNTS tab
    • Click the button at the bottom that saysGENERATE NEW PRIVATE KEY
    • This will download a.json file. You will now have access to the email and private key. You will pass those into the initialize during the next step.
  2. RegisterFerno as a Provider and importFerno. This is usually done inconfigure.swift

FirebaseSDK setup

  1. Log into the Firebase console
  2. Click the settings gear next toProject Overview
  3. SelectProject settings
  4. Select theSERVICE ACCOUNTS tab
  5. SelectFirebase Admin SDK option
  6. Click the buttonGenerate new private key to download the json file.

Ferno setup

You can use the content of json file information to fill out theFernoDefaultConfiguration or use the json file to preper theFernoServiceJsonConfiguration.

import FernoletfernoConfiguration=FernoDefaultConfiguration(    basePath:"database-url",     email:"service-account-email",     privateKey:"private-key")app.ferno.use(.default(fernoConfiguration))

If you prefer to use the FirebaseServiceAccount.json follow the example below.

import Ferno// option 1letfernoConfiguration=tryFernoServiceJsonConfiguration(json: Data)// option 2letfernoConfiguration=tryFernoServiceJsonConfiguration(path: URL)// option 3letfernoConfiguration=FernoServiceJsonConfiguration(                type: String,                projectId: String,                privateKeyId: String,                privateKey: String,                clientEmail: String,                clientId: String,                authUri: String,                tokenUri: String,                authProviderX509CertUrl: String,                clientX509CertUrl: String,                universeDomain: String)app.ferno.use(.serviceAccountKey(fernoConfiguration))

Parameters

There are some custom parameters to pass into functions. I want to go over all the parameters you will need to know.

[FernoQuery]

In GET requests, you might want to query on your data. This is what[FernoQuery] is for.

FernoQuery is an enum with:

  1. case shallow(Bool)
  2. case orderBy(FernoValue)
  3. case limitToFirst(FernoValue)
  4. case limitToLast(FernoValue)
  5. case startAt(FernoValue)
  6. case endAt(FernoValue)
  7. case equalTo(FernoValue)

These are all the possible queries that are allowed on Firebase according to thedocs

NOTES on [FernoQuery]

  • shallow(Bool) cannot be mixed with any other query parameters.
  • you usually useorderBy(FernoValue) in conjunction with enums3-7
  • usingorderBy(FernoValue) alone will just order the data returned

FernoValue

You will notice most cases inFernoQuery have a value ofFernoValue.FernoValue is just a wrapper forBool, String, Int, Double, Float. So you can just do.startAt(5) and everything will work.

Examples of [FernoQuery]

Just using shallow:

[.shallow(true)]

Filter data to only return data that matches"age": 21:

[.orderBy("age"),.equalTo(21)]

Just orderBy(returns data in ascending order):

[.orderBy("age")]

Usage

There are 6 functions that allow you to interact with your Firebase realtime database.

GET

There are four functions that allow you get your data.

app.ferno.retrieve(_ path:[String], queryItems:[FernoQuery]=[])
app.ferno.retrieve(_ path: String..., queryItems:[FernoQuery]=[])
app.ferno.retrieveMany(_ path:[String], queryItems:[FernoQuery]=[])
app.ferno.retrieveMany(_ path: String..., queryItems:[FernoQuery]=[])

The only difference betweenretrieve andretrieveMany is the return type.

  • retrieve returns ->F whereF is of typeDecodable
  • retrieveMany returns ->[String: F] whereF is of typeDecodable andString is the key

Example

  1. Define the value you want the data converted.
structDeveloper:Content{varname:StringvarfavLanguage:Stringvarage:Int}
  1. Make the request. Make sure you set the type of the response so Ferno knows what to convert.
letdevelopers:[String:Developer]=tryawait app.ferno.retrieveMany("developers")letdeveloper:Developer=tryawait app.ferno.retrieve(["developers","dev1"])

POST

Used to create a new entry in your database

app.ferno.create(_ path:[String], body: T)tryawait-> FernoChild
app.ferno.create(_ path: String..., body: T)tryawait-> FernoChild
  • body: T is of typeContent.
  • FernoChild is a struct:
structFernoChild:Content{varname:String}
  • FernoChild is returned, because the API request returns the key from the newly created child.

Example

letnewDeveloper=Developer(name:"Elon", favLanguage:"Python", age:46) // conforms to ContentletnewDeveloperKey:FernoChild=tryawait app.ferno.create("developers", body: newDeveloper)

DELETE

Used to delete an entry in your database

app.ferno.delete(_ path:[String])tryawait-> Bool
app.ferno.delete(_ path: String...)tryawait-> Bool
  • the delete method will return a boolean depending on if the delete was successful

Example

letsuccessfulDelete:Bool=tryawait app.ferno.delete(["developers","dev-1"])

PATCH

Update values at a specific location, but omitted values won't get removed

app.ferno.update(_ path:[String], body: T)tryawait-> T
app.ferno.update(_ path: String..., body: T)tryawait-> T
  • the update method will return the body

Example

structUpdateDeveloperName:Content{varname:String}letnewDeveloperName=UpdateDeveloperName(name:"Kimbal") //conforms to ContentletupdatedDeveloperName:UpdateDeveloperName=tryawait app.ferno.update(["developers", newDeveloperKey.name], body: newDeveloper) //newDeveloperKey.name comes from the create method

PUT

Overwrite the current location with data you are passing in

client.ferno.overwrite(_ path:[String], body: T)tryawait-> T
client.ferno.overwrite(_ path: String..., body: T)tryawait-> T

Example

structLeadDeveloper:Content{varname:Stringvarcompany:Stringvarage:Int}letleadDeveloper=LeadDeveloper(name:"Ashley", company:"Bio-Fit", age:20)letleadDevResponse:LeadDeveloper=tryawait app.ferno.overwrite(["developers", newDeveloperKey.name], body: leadDeveloper)

Testing

Currently, tests were written using an actual dummy Firebase realtime database. If you want to run all of the tests, you will need to create a dummy Firebase realtime database.

Testing Setup

You need to go toApplication+Testing.swift and fill in the missing values based on your Firebase service account. Then you will be able to run tests.

Authors

License

This project is licensed under the MIT License - see theLICENSE.md file for details

Acknowledgments

  • Vapor Discord (for helping me with all my issues <3)
  • Stripe Provider as a great template!stripe-provider

[8]ページ先頭

©2009-2025 Movatter.jp