appres

package module
v0.0.11-alpha Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2025 License: GPL-3.0 Imports: 10 Imported by: 0

README

AppRes - Appwrite Resource Creator

A Go package for creating and managing Appwrite resources programmatically. Simplifies creating databases, collections, attributes, and storage buckets with built-in duplicate checking.

Features

  • Databases: Create with duplicate checking
  • Collections: Create within databases with duplicate checking
  • Attributes: Support for string, email, integer, datetime, boolean, relationship, and url types
  • Storage: Create buckets with security and file constraints
  • Environment-based configuration
  • Built-in error handling and logging

Installation

go get github.com/Haepapa/appres

Setup

Create a .env.local file in your project root with:

APPWRITE_ENDPOINT_URL=https://your-appwrite-endpoint.com/v1
APPWRITE_PROJECT_ID=your-project-id
APPWRITE_API_KEY_APPRES=your-api-key  # API key with Database and Storage scopes

Import

import (
    "log"
    app "github.com/Haepapa/appres"
)

Usage

package main

import (
    "log"
    app "github.com/Haepapa/appres"
)

func main() {
    // Initialize Appwrite client
    app.Utils()

    // Create database
    db, err := app.CreateDatabase("my-database")
    if err != nil {
        log.Fatal(err)
    }

    // Create collection
    col, err := app.CreateCollection(db.Id, "users")
    if err != nil {
        log.Fatal(err)
    }

    // Create attribute
    attr := app.AttributeType{
        Type:     "string",
        Name:     "username",
        Size:     50,
        Required: true,
    }
    err = app.CreateAttribute(db.Id, col.Id, attr)
    if err != nil {
        log.Fatal(err)
    }

    // Create storage bucket
    bucket := app.BucketType{
        Name:         "user-uploads",
        Enabled:      true,
        FileSecurity: true,
        MaxFileSize:  10000000, // 10MB
    }
    buc, err := app.CreateBucket(bucket)
    if err != nil {
        log.Fatal(err)
    }

    log.Println("Resources created successfully!")
}

API Reference

Functions
Function Description
Utils() Initialize Appwrite client (required first)
CreateDatabase(name) Create database with duplicate checking
CreateCollection(dbId, name) Create collection with duplicate checking
CreateAttribute(dbId, colId, attr) Create attribute with duplicate checking
CreateBucket(bucket) Create storage bucket
Attribute Types
Type Fields Example
string Size, Encrypt Text with optional encryption
email Size Email validation
integer Min, Max Numbers with constraints
datetime Date and time values
boolean True/false values
relationship RelatedCollectionID, RelationshipType Link collections
url URL validation

Common Fields: Type, Name, Required, Default, Array

Environment Variables

Variable Description
APPWRITE_ENDPOINT_URL Your Appwrite server endpoint URL
APPWRITE_PROJECT_ID Your Appwrite project ID
APPWRITE_API_KEY_APPRES API key with Database and Storage permissions

Requirements

  • Go 1.22.5 or later
  • Active Appwrite server instance
  • Valid API key with appropriate permissions

License

Licensed under the terms in the LICENSE file.

Contributing

Contributions welcome! Please submit a Pull Request.

Documentation

Overview

Package appres provides utilities for creating and managing Appwrite resources programmatically. It simplifies the process of creating various resources in your Appwrite backend.

This package offers a simplified interface to the Appwrite Go SDK, providing functions to:

  • Initialize the Appwrite client
  • Create databases with duplicate checking
  • Create collections within databases
  • Create various types of attributes (string, email, integer, datetime, boolean, relationship, url)
  • Create storage buckets with security and file constraints

All functions include built-in duplicate checking to prevent errors when resources already exist.

Basic Usage:

package main

import (
	"log"
	"github.com/Haepapa/appres"
)

func main() {
	// Initialize the Appwrite client (required first step)
	appres.Utils()

	// Create a database
	db, err := appres.CreateDatabase("my-database")
	if err != nil {
		log.Fatal(err)
	}

	// Create a collection
	col, err := appres.CreateCollection(db.Id, "my-collection")
	if err != nil {
		log.Fatal(err)
	}

	// Create attributes
	attr := appres.AttributeType{
		Type:     "string",
		Name:     "title",
		Size:     255,
		Required: true,
	}
	err = appres.CreateAttribute(db.Id, col.Id, attr)
	if err != nil {
		log.Fatal(err)
	}
}

Environment Setup:

Before using this package, create a .env.local file in your project root with:

APPWRITE_ENDPOINT_URL=https://your-appwrite-endpoint.com/v1
APPWRITE_PROJECT_ID=your-project-id
APPWRITE_API_KEY_APPRES=your-api-key

The API key should have all permissions on database and storage objects in Appwrite.

Index

Constants

This section is empty.

Variables

View Source
var (
	AppwriteDatabase *databases.Databases
	AppwriteStorage  *storage.Storage
)

AppwriteDatabase is the global database client instance used by all database operations. It is initialised by calling Utils() and should not be accessed directly.

Functions

func CreateAttribute

func CreateAttribute(dbID string, colID string, att AttributeType) error

CreateAttribute creates a new attribute in the specified collection or skips creation if it already exists. It checks for duplicates to avoid errors and supports all major attribute types.

Parameters:

  • dbID: The ID of the database containing the collection
  • colID: The ID of the collection where the attribute should be created
  • att: AttributeType struct containing the attribute configuration

Global Variables Used:

  • AppwriteDatabase: The initialized Appwrite database client

Returns:

  • error: Any error that occurred during the operation, or nil if successful

Supported types: string, email, integer, datetime, boolean, relationship, url

Example:

attr := app.AttributeType{
	Type:     "string",
	Name:     "title",
	Size:     255,
	Required: true,
	Default:  "",
	Array:    false,
	Encrypt:  false,
}
err := app.CreateAttribute(db.Id, col.Id, attr)
if err != nil {
	log.Fatal("Failed to create attribute:", err)
}

func CreateBucket

func CreateBucket(buc BucketType) (*models.Bucket, error)

CreateBucket creates a new storage bucket with the specified configuration. It creates a bucket with customizable security, file size limits, and permissions.

Parameters:

  • buc: BucketType struct containing the bucket configuration

Global Variables Used:

  • AppwriteStorage: The initialized Appwrite storage client

Returns:

  • *models.Bucket: Pointer to the created bucket
  • error: Any error that occurred during the operation

Example:

bucket := appres.BucketType{
	Name:         "my-bucket",
	Enabled:      true,
	FileSecurity: true,
	MaxFileSize:  10000000, // 10MB
	Permissions:  []string{"read(\"any\")"},
}
buc, err := appres.CreateBucket(bucket)
if err != nil {
	log.Fatal("Failed to create bucket:", err)
}

func CreateCollection

func CreateCollection(dbId string, name string) (*models.Collection, error)

CreateCollection creates a new collection in the specified database or returns the existing one if it already exists. It first checks if a collection with the given name already exists in the database to avoid duplicates.

The function automatically generates a unique ID for new collections and logs the creation process.

Parameters:

  • dbId: The ID of the database where the collection should be created
  • name: The name of the collection to create

Global Variables Used:

  • AppwriteDatabase: The initialized Appwrite database client

Returns:

  • *models.Collection: Pointer to the created or existing collection
  • error: Any error that occurred during the operation

Example:

col, err := app.CreateCollection(db.Id, "users")
if err != nil {
	log.Fatal("Failed to create collection:", err)
}
fmt.Printf("Collection created with ID: %s\n", col.Id)

func CreateDatabase

func CreateDatabase(name string) (*models.Database, error)

CreateDatabase creates a new database with the specified name or returns the existing one if it already exists. It first checks if a database with the given name already exists to avoid duplicates.

The function automatically generates a unique ID for new databases and logs the creation process.

Parameters:

  • name: The name of the database to create

Global Variables Used:

  • AppwriteDatabase: The initialized Appwrite database client

Returns:

  • *models.Database: Pointer to the created or existing database
  • error: Any error that occurred during the operation

Example:

db, err := app.CreateDatabase("my-app-database")
if err != nil {
	log.Fatal("Failed to create database:", err)
}
fmt.Printf("Database created with ID: %s\n", db.Id)

func Utils

func Utils()

Utils initialises the Appwrite client with configuration from environment variables. It loads environment variables from the .env.local file and creates a new Appwrite client with the configured endpoint, project ID, and API key.

This function must be called before using any other functions in this package. It will terminate the program if the .env.local file cannot be loaded.

Environment variables required:

  • APPWRITE_ENDPOINT_URL: The Appwrite server endpoint URL
  • APPWRITE_PROJECT_ID: The Appwrite project ID
  • APPWRITE_API_KEY_APPRES: The API key with database and storage permissions

Example:

app.Utils()
// Now you can use other functions such as CreateDatabase, CreateCollection, etc.

Types

type AttributeType

type AttributeType struct {
	// Type specifies the attribute type. Supported values: "string", "email", "integer", "datetime", "boolean"
	Type string

	// Name is the key/identifier for the attribute in the collection
	Name string

	// Size defines the maximum length for string and email attributes
	Size int

	// Required determines whether this attribute must have a value
	Required bool

	// Default is the default value assigned to the attribute if no value is provided
	Default interface{}

	// Array indicates whether the attribute can store multiple values as an array
	Array bool

	// Encrypt determines whether the attribute value should be encrypted at rest
	// Note: Only available for string attributes
	Encrypt bool

	// Min is the minimum value for integer attributes (optional)
	// If not set (0), no minimum constraint will be applied
	Min interface{}

	// Max is the maximum value for integer attributes (optional)
	// If not set (0), no maximum constraint will be applied
	Max interface{}

	// The ID of the collection this relationship attribute links to.
	RelatedCollectionID string

	// The type of relationship
	// must be one of; `oneToOne`, `oneToMany`, `manyToOne`, `manyToMany`.
	// Reference documentation: https://appwrite.io/docs/products/databases/relationships#types
	RelationshipType string

	// Enable two-way directionality
	// false: One-way - The relationship is only visible to one side of the relation. This is similar to a tree data structure.
	// true:  Two-way - The relationship is visible to both sides of the relationship. This is similar to a graph data structure.
	// Reference documentation: https://appwrite.io/docs/products/databases/relationships#directionality
	TwoWay bool

	// The key/identifier used to name the two-way relationship on the related collection side.
	TwoWayKey string

	// On delete constraint behaviour for relationship attributes
	// must be one of; `restrict`, `cascade`, `setnull`.
	// Restrict: If a row has at least one related row, it cannot be deleted.
	// Cascade:	If a row has related rows, when it is deleted, the related rows are also deleted.
	// Set null: If a row has related rows, when it is deleted, the related rows are kept with their relationship column set to null.
	// Reference documentation: https://appwrite.io/docs/products/databases/relationships#on-delete
	OnDelete string
}

AttributeType defines the configuration for creating attributes in Appwrite collections. It contains all the necessary fields to specify the type, constraints, and behavior of an attribute when creating it in a collection.

Supported attribute types:

  • "string": Text attributes with size, encryption, and array support
  • "email": Email validation attributes with array support
  • "integer": Integer attributes with min/max constraints and array support
  • "datetime": Date and time attributes with array support
  • "boolean": Boolean (true/false) attributes with array support
  • "relationship": Relationship attributes linking collections
  • "url": URL validation attributes with array support

Example usage:

attr := AttributeType{
	Type:     "string",
	Name:     "username",
	Size:     50,
	Required: true,
	Default:  "",
	Array:    false,
	Encrypt:  false,
}

// Integer attribute example:
intAttr := AttributeType{
	Type:     "integer",
	Name:     "age",
	Required: true,
	Min:      0,
	Max:      120,
	Default:  "18",
	Array:    false,
}

type BucketType

type BucketType struct {
	// Name is the bucket identifier
	Name string

	// Permissions is an array of permission strings (e.g. "read(\"any\")")
	Permissions []string

	// FileSecurity enables file-level security permissions
	FileSecurity bool

	// Enabled determines if the bucket is accessible to users
	Enabled bool

	// MaxFileSize is the maximum file size allowed in bytes (max: 30MB)
	MaxFileSize int

	// AllowedFileExtensions limits file types (max: 100 extensions)
	AllowedFileExtensions []string

	// Compression algorithm: "none", "gzip", or "zstd"
	Compression string

	// Encryption enables file encryption at rest
	Encryption bool

	// Antivirus enables virus scanning for uploaded files
	Antivirus bool
}

BucketType defines the configuration for creating storage buckets in Appwrite. It contains all the necessary fields to specify bucket behavior, security, and constraints.

Example usage:

bucket := BucketType{
	Name:         "user-uploads",
	Enabled:      true,
	FileSecurity: true,
	MaxFileSize:  10000000, // 10MB
	Permissions:  []string{"read(\"any\")"},
	Compression:  "gzip",
	Encryption:   true,
	Antivirus:    true,
}

Directories

Path Synopsis
Package helper provides utility functions for loading and managing environment variables required for Appwrite client configuration.
Package helper provides utility functions for loading and managing environment variables required for Appwrite client configuration.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL