appres

package module
v0.0.3 Latest Latest
Warning

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

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

README

AppRes - Appwrite Resource Creator

A Go package for creating and managing Appwrite resources programmatically. This package simplifies the process of creating databases, collections, and attributes in your Appwrite backend.

Features

  • Create databases with duplicate checking
  • Create collections with duplicate checking
  • Create attributes with full configuration support for multiple types:
    • String attributes with size, encryption, and array support
    • Email attributes with validation and array support
    • Integer attributes with min/max constraints and array support
    • DateTime attributes with default values and array support
    • Boolean attributes with default values and array support
  • Environment-based configuration
  • Comprehensive error handling and logging

Installation

Install the package using go get:

go get github.com/Haepapa/appres

Setup

1. Environment Configuration

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

NEXT_PUBLIC_APPWRITE_ENDPOINT=https://your-appwrite-endpoint.com/v1
NEXT_PUBLIC_APPWRITE_PROJECT=your-project-id
APPWRITE_API_KEY_RESDEF=your-api-key #api key with all Database scopes
2. Import the Package
import (
    "crypto/tls"
    "log"
    "net/http"
    
    app "github.com/Haepapa/appres"
)

Usage

Basic Example

Here's a complete example showing how to create a database, collection, and attributes:

package main

import (
    "crypto/tls"
    "log"
    "net/http"
    
    app "github.com/Haepapa/appres"
)

func main() {
    // Suppress insecure warning (if using self-signed certificates)
    http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}

    // Initialize Appwrite client
    app.Utils()

    // Create a database
    db, err := app.CreateDatabase("synergysquares")
    if err != nil {
        log.Println("Error creating database:", err)
        return
    }

    // Create collection(s)
    colContactUs, err := app.CreateCollection(db.Id, "contact_us")
    if err != nil {
        log.Println("Error creating collection:", err)
        return
    }

    // Create attributes in collection(s)
    attVals := []app.AttributeType{
        {
            Type:        "string",
            Name:        "name",
            Size:        100,
            Required:    false,
            Default:     "",
            Array:       false,
            Encrypt:     false,
        },
        {
            Type:        "email",
            Name:        "email",
            Size:        200,
            Required:    false,
            Default:     "email@email.com",
            Array:       false,
            Encrypt:     false,
        },
        {
            Type:        "string",
            Name:        "subject",
            Size:        200,
            Required:    false,
            Default:     "",
            Array:       false,
            Encrypt:     false,
        },
        {
            Type:        "string",
            Name:        "message",
            Size:        5000,
            Required:    false,
            Default:     "",
            Array:       false,
            Encrypt:     false,
        },
        {
            Type:        "integer",
            Name:        "priority",
            Required:    false,
            Default:     "1",
            Min:         1,
            Max:         5,
            Array:       false,
        },
        {
            Type:        "datetime",
            Name:        "created_at",
            Required:    true,
            Array:       false,
        },
        {
            Type:        "boolean",
            Name:        "is_resolved",
            Required:    false,
            Default:     "false",
            Array:       false,
        },
    }

    for _, att := range attVals {
        err = app.CreateAttribute(db.Id, colContactUs.Id, att)
        if err != nil {
            log.Println("Error creating attribute:", err)
            return
        }
    }

    log.Println("Successfully created database, collection, and attributes!")
}

API Reference

Functions
Utils()

Initializes the Appwrite client with environment variables. Must be called before using other functions.

app.Utils()
CreateDatabase(name string) (*models.Database, error)

Creates a new database or returns existing one if it already exists.

db, err := app.CreateDatabase("my-database")
if err != nil {
    log.Fatal(err)
}
fmt.Println("Database ID:", db.Id)
CreateCollection(dbId string, name string) (*models.Collection, error)

Creates a new collection in the specified database or returns existing one if it already exists.

col, err := app.CreateCollection(db.Id, "my-collection")
if err != nil {
    log.Fatal(err)
}
fmt.Println("Collection ID:", col.Id)
CreateAttribute(dbID string, colID string, att AttributeType) error

Creates a new attribute in the specified collection or skips if it already exists.

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(err)
}
Attribute Examples

Here are examples of creating different attribute types:

// String attribute with encryption
stringAttr := app.AttributeType{
    Type:     "string",
    Name:     "username",
    Size:     50,
    Required: true,
    Default:  "",
    Array:    false,
    Encrypt:  true,
}

// Email attribute
emailAttr := app.AttributeType{
    Type:     "email",
    Name:     "user_email",
    Size:     255,
    Required: true,
    Default:  "",
    Array:    false,
}

// Integer attribute with min/max constraints
integerAttr := app.AttributeType{
    Type:     "integer",
    Name:     "age",
    Required: false,
    Default:  "18",
    Min:      0,
    Max:      120,
    Array:    false,
}

// DateTime attribute
datetimeAttr := app.AttributeType{
    Type:     "datetime",
    Name:     "created_at",
    Required: true,
    Array:    false,
}

// Boolean attribute
booleanAttr := app.AttributeType{
    Type:     "boolean",
    Name:     "is_active",
    Required: false,
    Default:  "true",
    Array:    false,
}

// Array attribute example
arrayAttr := app.AttributeType{
    Type:     "string",
    Name:     "tags",
    Size:     50,
    Required: false,
    Array:    true, // This creates an array of strings
}
Types
AttributeType

Defines the structure for creating attributes:

type AttributeType struct {
    Type     string // Supported: "string", "email", "integer", "datetime", "boolean"
    Name     string // Attribute key/name
    Size     int    // Maximum size (for string/email attributes)
    Required bool   // Whether the attribute is required
    Default  string // Default value
    Array    bool   // Whether the attribute is an array
    Encrypt  bool   // Whether to encrypt the attribute (string only)
    Min      int    // Minimum value (for integer attributes)
    Max      int    // Maximum value (for integer attributes)
}
Supported Attribute Types
  • string: Text attributes with configurable size, encryption, and array support

    • Size: Maximum character length (required)
    • Encrypt: Enable encryption at rest (optional)
    • Default: Default string value (optional)
  • email: Email validation attributes with array support

    • Size: Maximum character length (required)
    • Default: Default email value (optional)
  • integer: Integer attributes with configurable min/max constraints and array support

    • Min: Minimum allowed value (optional, 0 = no constraint)
    • Max: Maximum allowed value (optional, 0 = no constraint)
    • Default: Default integer value as string (optional)
  • datetime: Date and time attributes with default values and array support

    • Default: Default datetime value in ISO 8601 format (optional)
  • boolean: Boolean (true/false) attributes with default values and array support

    • Default: Default boolean value as string "true" or "false" (optional)

Common Configuration Options:

  • Required: Whether the attribute must have a value (all types)
  • Array: Whether the attribute stores multiple values as an array (all types)

Environment Variables

Variable Description Required
NEXT_PUBLIC_APPWRITE_ENDPOINT Your Appwrite server endpoint URL Yes
NEXT_PUBLIC_APPWRITE_PROJECT Your Appwrite project ID Yes
APPWRITE_API_KEY_RESDEF API key with appropriate permissions Yes

Error Handling

All functions return appropriate errors that should be handled:

db, err := app.CreateDatabase("test-db")
if err != nil {
    log.Printf("Failed to create database: %v", err)
    return
}

The package also provides detailed logging for debugging purposes.

Requirements

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

License

This project is licensed under the terms included in the LICENSE file.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Documentation

Overview

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

Usage:

app.Utils()
db, err := app.CreateDatabase("my-database")
if err != nil {
	log.Fatal(err)
}
col, err := app.CreateCollection(db.Id, "my-collection")
if err != nil {
	log.Fatal(err)
}

Index

Constants

This section is empty.

Variables

View Source
var (
	AppwriteDatabase *databases.Databases
)

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 first checks if an attribute with the given name already exists in the collection to avoid duplicates.

The function supports creating string and email attributes with full configuration options including size limits, default values, array types, and encryption settings.

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

Returns:

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

Supported attribute types:

  • "string": Text attributes with configurable size, defaults, arrays, and encryption
  • "email": Email validation attributes with defaults and array support

References:

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 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

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

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:

  • NEXT_PUBLIC_APPWRITE_ENDPOINT: The Appwrite server endpoint URL
  • NEXT_PUBLIC_APPWRITE_PROJECT: The Appwrite project ID
  • APPWRITE_API_KEY_RESDEF: The API key with appropriate 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{}

	RelatedCollectionID string

	RelationshipType string

	TwoWay bool

	TwoWayKey string

	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 configurable size limits
  • "email": Email validation attributes
  • "integer": Integer attributes with configurable min/max constraints
  • "datetime": Date and time attributes
  • "boolean": Boolean (true/false) attributes

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,
}

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