@flowerforce/flowerbase-client
v0.1.0
Published
Client for Flowerbase
Readme
@flowerforce/flowerbase-client
Client TypeScript leggero per usare Flowerbase con API in stile Realm:
- autenticazione (
local-userpass,anon-user,custom-function) - chiamate funzioni (
user.functions.<name>(...)) - accesso a MongoDB Atlas service (
user.mongoClient("mongodb-atlas")) - change stream via
watch()con async iterator - supporto BSON/EJSON (
ObjectId,Date, ecc.)
Installazione
npm i @flowerforce/flowerbase-clientQuick start
import { App, Credentials } from '@flowerforce/flowerbase-client'
const app = new App({
id: 'my-app-id',
baseUrl: 'http://localhost:8000',
timeout: 10000
})
await app.logIn(Credentials.emailPassword('[email protected]', 'secret'))
const user = app.currentUser
if (!user) throw new Error('User not logged in')
const result = await user.functions.myFunction('hello')
console.log(result)Configurazione App
new App({
id: string, // app id Flowerbase
baseUrl: string, // URL base backend (es: http://localhost:8000)
timeout?: number // default 10000
})Autenticazione
Local user/pass
await app.logIn(Credentials.emailPassword(email, password))Anonymous
await app.logIn(Credentials.anonymous())Custom function auth
await app.logIn(
Credentials.function({
username: 'demo',
pin: '1234'
})
)Utility emailPasswordAuth
await app.emailPasswordAuth.registerUser({ email, password })
await app.emailPasswordAuth.sendResetPasswordEmail(email)
await app.emailPasswordAuth.callResetPasswordFunction(email, newPassword, extraArg1, extraArg2)
await app.emailPasswordAuth.resetPassword({ token, tokenId, password })Current user
Dopo il login:
const user = app.currentUserInterfaccia principale:
user.iduser.functions.<functionName>(...args)user.mongoClient('mongodb-atlas')user.refreshAccessToken()user.refreshCustomData()user.logOut()
Funzioni server
const response = await user.functions.calculateScore({ workspaceId: 'w1' })Le risposte sono normalizzate lato client per gestire payload JSON/EJSON.
Mongo service
const mongo = user.mongoClient('mongodb-atlas')
const collection = mongo.db('mydb').collection('todos')
const one = await collection.findOne({ done: false })
const many = await collection.find({ done: false })
await collection.insertOne({ title: 'Task', createdAt: new Date() })
await collection.updateOne({ title: 'Task' }, { $set: { done: true } })
await collection.deleteOne({ title: 'Task' })Metodi disponibili su collection:
find(query?, options?)findOne(query?, options?)insertOne(document, options?)updateOne(filter, update, options?)updateMany(filter, update, options?)deleteOne(filter, options?)watch(options?)
Watch / Change streams
watch() restituisce un async iterator con reconnect automatico e metodo close().
const stream = collection.watch()
try {
for await (const change of stream) {
console.log(change)
}
} finally {
stream.close()
}Esempio con filtro Realm-like:
const stream = collection.watch({
filter: {
operationType: 'update',
'fullDocument.type': 'perennial'
}
})BSON / EJSON
Il client esporta anche:
import { BSON, EJSON, ObjectId, ObjectID } from '@flowerforce/flowerbase-client'Il layer Mongo client serializza query/opzioni con EJSON e deserializza le risposte, così tipi BSON come ObjectId e Date restano coerenti con l'uso Realm-like.
Sessione
La sessione (accessToken, refreshToken, userId) viene salvata con chiave:
flowerbase:<appId>:session
Storage usato:
localStoragese disponibile (browser)- memory store fallback (ambienti senza
localStorage)
Su bootstrap dell'app viene tentato un refresh automatico dell'access token usando il refresh token salvato.
Logout
await user.logOut()Invia DELETE /auth/session con refresh token e pulisce la sessione locale.
Tipi esportati
AppConfigCredentialsLikeUserLikeMongoClientLikeCollectionLikeWatchAsyncIterator
Build e test (workspace)
npm run build --workspace @flowerforce/flowerbase-client
npm run test --workspace @flowerforce/flowerbase-clientOppure dal package:
npm run build
npm test