laf Documentation

repository·main·Indexed 27 days ago

https://github.com/labring/laf

An open-source serverless cloud development platform providing cloud functions, databases, and storage. Includes documentation for the laf-cli management tool and the laf-client-sdk for JavaScript, featuring comprehensive guides on database operations, advanced querying with db.command, relational queries, and GEO data types.

Tokens
46.6K
Snippets
77
Records
472
Agent score
93%

What's inside laf

  1. Overview of `laf` Cloud Development Platform

    main

    laf is an open-source cloud development platform designed to provide ready-to-use application resources. It enables developers to focus on business logic by providing managed services, reducing the need for server maintenance and infrastructure configuration.

    Key managed resources include:

    • Cloud Functions: Write and deploy code as functions.
    • Cloud Database: Managed database services.
    • Cloud Storage: Managed file storage.
    • WebIDE: An integrated development environment for writing code directly in the browser.
    • Website Hosting: Static website hosting for front-end applications.
    • WebSocket Support: Real-time communication capabilities.
  2. Understand the role of laf server

    main

    laf server is the core component responsible for the laf HTTP API. It manages the following domains:

    • Auth & User: Authentication and user management.
    • Region Cluster: Management of regional clusters.
    • App Management: Core application lifecycle.
    • Cloud Functions: Management of app cloud functions.
    • Database: Management of app databases.
    • Storage: Management of app storage.
    • Logs: Management of app logs.
    • Instances: Management of app instances.
    • Billing: Management of app billing.
    • Domains: Management of app domains.
    • Certificates: Management of app certificates.
    • Metrics: Management of app metrics.
  3. Laf Web Tech Stack Overview

    main

    The laf web application is built using the following technologies:

    • Base Framework: React / Next.js 12.x (planned update to 13.x)
    • Data Fetching: react-query + axios
    • State Management: zustand + immer
    • Internationalization (i18n): lingui
    • UI Components: chakra-ui
    • Styling: tailwind + sass
    • Icons: react-icons
    • Developer Experience (DX): click-to-component
  4. Implement database-proxy on the server

    main

    To use database-proxy on your server, you need to set up an Accessor (e.g., MongoAccessor), a Policy containing your access control rules, and a Proxy instance. The proxy handles parameter parsing, validation against rules, and execution.

    const app = require('express')()
    const { Proxy, MongoAccessor, Policy } = require('database-proxy')
    const { MongoClient } = require('mongodb')
    
    app.use(express.json())
    
    // design the access control policy rules
    const rules = {
        categories: {
            "read": true,
            "update": "!uid",
            "add": "!uid",
            "remove": "!uid"
        }
    }
    
    const client = new MongoClient('mongodb://localhost:27017')
    client.connect()
    
    // create an accessor
    const accessor = new MongoAccessor(client)
    
    // create a policy
    const policy = new Policy(accessor)
    policy.load(rules)
    
    // create an proxy
    const proxy = new Proxy(accessor, policy)
    
    app.post('/proxy', async (req, res) => {
      const { uid } = parseToken(req.headers['authorization'])
    
      const injections = {
        uid: uid
      }
    
      // parse params
      const params = proxy.parseParams(req.body)
    
      // validate query
      const result = await proxy.validate(params, injections)
      if (result.errors) {
        return res.send({
          code: 1,
          error: result.errors
        })
      }
    
      // execute query
      const data = await proxy.execute(params)
      return res.send({
        code: 0,
        data
      })
    })
    
    app.listen(8080, () => console.log('listening on 8080'))
  5. Handle Logical Deletion in Queries

    main

    When working with data that uses a logical delete flag (e.g., del_flag), you can configure how queries interact with deleted records:

    • Default Un-deleted View: To default queries to only show non-deleted data, use default: 0. Note that this does not prevent a user from explicitly querying deleted data if they provide a different del_flag value.
    • Strictly Prohibit Deleted Data: To prevent users from accessing deleted records entirely, set required: true and a condition that excludes the deleted state (e.g., condition: "$value != 1").
    • Override: Use override to force a specific value for the deletion flag.
    // Default to non-deleted (del_flag: 0)
    query: {
      del_flag: { default: 0 }
    }
    
    // Force user to only query non-deleted data
    query: {
      del_flag: {
        condition: "$value != 1",
        required: true
      }
    }
    
    // Force the query to use a specific del_flag value
    query: {
      del_flag: { override: 1 }
    }
  6. Use @lafjs/cloud in Cloud Functions

    main

    The @lafjs/cloud package is used within Cloud Functions to expose resource objects (such as databases) to the function execution context. You can import cloud and use its methods to interact with managed resources like cloud.database().

    import cloud from '@lafjs/cloud'
    
    exports.main = async function (ctx) {
    
      const db = cloud.database()
      const res = await db.collection('messages').get()
    
      return res.data
    }
  7. Develop the Node.js runtime locally

    main

    To develop the runtime-nodejs service locally, you must proxy traffic from your running laf cluster to your local machine using Telepresence. This allows you to test cloud functions and database access proxying in a local environment that behaves as if it were inside the cluster.

    Prerequisites

    • A laf cluster installed (configured in ~/.kube/config).
    • Telepresence installed.
    • A running application appid in the laf cluster.
    • Node.js version >= 18.0.0.

    Setup and Execution Steps

    1. Navigate to the runtime directory.
    2. Connect to the laf-system namespace using Telepresence.
    3. Set your appid environment variable.
    4. Intercept the traffic for your specific appid and map it to local port 8000.
    5. Install dependencies, build, and start the service.

    Cleanup

    When finished, leave the intercepted application and uninstall Telepresence components to restore your network state.

    cd runtimes/nodejs
    
    # Connect to the cluster
    telepresence connect -n laf-system
    
    # Set your appid
    export appid=your-app-id
    
    # Proxy app cluster traffic to local
    telepresence intercept $appid -p 8000:8000 -e $(pwd)/.env
    
    # Verify intercept is active
    telepresence list
    
    # Install and start local service
    npm install
    npm run build
    npm start