AirCode Documentation

website·Indexed 34 days ago

https://docs.aircode.io

Documentation for AirCode's cloud development platform, featuring an in-browser IDE for building and deploying cloud functions. Includes guides and API references for the `aircode.db` database API, `aircode.files` file storage API, TypeScript support, scheduled tasks, and NPM dependency management.

Tokens
22.7K
Snippets
119
Records
172
Agent score
57%

What's inside AirCode

  1. Use AirCode's built-in schema-free database

    AirCode provides an integrated database accessible via aircode.db within cloud functions. It is schema-free, meaning you do not need to define fields or tables in advance; you can store data directly, and AirCode automatically identifies the schema information. No separate purchase, configuration, or connection steps are required.
    const MyTable = aircode.db.table('myTable');
    const item = await MyTable.save({
      name: 'Macbook Air',
      quantities: 25,
    });
  2. Understand AirCode cloud function runtime and environment

    AirCode provides an in-browser IDE for development. Cloud functions are written in JavaScript and execute in a Node.js runtime environment. Files with a .js extension are treated as cloud functions and generate an online URL API. Non-.js files (e.g., .json, .txt) are not treated as functions and are typically used for configuration and referenced via require in other functions.
  3. Access request metadata via the context object

    The context object provides metadata about the incoming HTTP request:

    • context.headers: An Object of request headers. Keys are always lowercase (e.g., context.headers['content-type']).
    • context.method: The HTTP method in uppercase (e.g., 'POST', 'GET').
    • context.path: The request path (e.g., /hello).
    • context.url: The full URL including path and query string (e.g., /hello?hi=aircode).
    • context.query: An Object of query string parameters (identical to params in GET requests).
    • context.cookies: An Object of request cookies as key-value pairs.
    • context.protocol: The protocol used (always https in AirCode).
    • context.trigger: The source of the call: 'HTTP', 'SCHEDULE', or 'DEBUG'.
    • context.request / context.req: The Node.js request object.
    • context.response / context.res: The Node.js response object.
    // Example: Accessing headers and query
    const contentType = context.headers['content-type'];
    const hello = context.query.hello;
  4. Understand AirCode auto-scaling and cold starts

    AirCode functions scale automatically based on request traffic. Available instances are used first; new instances are created when existing ones are fully loaded, and idle instances are recycled when traffic drops.

    Cold Starts: Applications not invoked for a period enter an idle state. The first request to an idle application triggers a 'cold start,' resulting in higher initial latency. Subsequent calls return to normal performance. Because the idle state is managed at the application level, calling any function within the same app prevents the entire application from entering the idle state.

  5. Extend AirCode capabilities using official and community extensions

    AirCode supports a range of extensions developed by the official team and the open-source community. These extensions allow developers to implement advanced functionality including custom routing, the development and deployment of web applications with frontend pages, and the ability to run Express and Koa applications. Detailed usage instructions for these extensions are maintained in the official GitHub repository.
  6. Invoke other functions from a cloud function

    Depending on the location of the target function, use one of the following methods:

    • Functions in the same App: Load the function using require.
    • Functions in different Apps: Invoke the cloud functions directly via HTTP.
  7. Query records using nested fields

    When a database field is an Object, use the dot (.) connector to query embedded fields. This supports multi-level nesting. Because of JavaScript syntax, keys containing dots must be wrapped in quotation marks.
    const aircode = require('aircode');
    
    module.exports = async function(params, context) {
      const InventoryTable = aircode.db.table('inventory');
      // Query based on the 'location' subfield within the 'info' object
      const result = await InventoryTable
        .where({ 'info.location': 'Beijing' })
        .find();
    
      return { result };
    }
  8. Download files from AirCode storage

    Use aircode.files.download(file) to retrieve the content of a file. The file parameter should be the file record (typically retrieved from the _files table). By default, the method returns the file content as a Buffer containing binary information. This is intended for temporary use during a request (e.g., text processing or watermarking).
    const aircode = require('aircode');
    
    module.exports = async function (params, context) {
      // Access the _files table to find the file record
      const FilesTable = aircode.db.table('_files');
      const file = await FilesTable.where({ name: 'hello.txt' }).findOne();
    
      // Download the file as a Buffer
      const content = await aircode.files.download(file);
    
      return {
        content,
      };
    }
  9. Generate and view logs for AirCode cloud functions

    Cloud functions generate logs using standard Node.js console methods. Once a function is deployed and triggered via its URL, logs are displayed in real-time within the Logs tab of the AirCode interface. Note that there may be a few seconds of delay in log collection.
    module.exports = async function(params, context) {
      // Print a general log with current time
      console.log('Hello World. Current time is:', new Date());
      
      // Print a log of Error level
      console.error('This is an error');
    
      return {
        message: 'Hi, AirCode.',
      };
    }
  10. Deploy environment variable changes to production

    Modifications made to environment variables in the AirCode console only take effect in the local environment immediately. To apply these changes to the online production environment, you must deploy the function.
  11. Download files in the browser

    The aircode.files.download method is only available in cloud functions. To download files in a browser environment, use a third-party HTTP library (like axios) to send a GET request to the file's CDN URL (found in the url field of the _files table). To trigger a local file save, use responseType: 'blob' in conjunction with a library like js-file-download.
    import axios from 'axios';
    import fileDownload from 'js-file-download';
    
    // Example: Download and save file locally in browser
    axios({
      url: 'https://sample.aircodecdn.com/hello.b10a8db164e07541.txt',
      method: 'GET',
      responseType: 'blob'
    }).then(response => {
      fileDownload(response.data, 'filename.txt');
    });
  12. Manage real-time log fetching and historical queries

    In the Logs tab, you can control how logs are displayed:

    • Real-time Fetching: By default, logs are fetched in real-time. Use the Pause button to stop the stream and the Resume button to restart fetching from the current timestamp.
    • Querying: Historical logs can be filtered and queried using dimensions such as date, keyword, or log level.