### FastSchema Setup URL Example Source: https://fastschema.com/docs/getting-started An example of the URL to access the FastSchema setup page, which includes a unique token generated upon the first run. The setup requires admin credentials. ```bash Visit the following URL to setup the app: http://localhost:8000/dash/setup/?token=anpDXDBymatYLIITreQgGaVdhLanpDXD ``` -------------------------------- ### Run FastSchema Development Server Source: https://fastschema.com/docs/getting-started Command to start the FastSchema development server using `make dev`. This command utilizes `air` for hot-reloading, which can be installed via `go install github.com/cosmtrek/air@latest`. ```bash make dev ``` -------------------------------- ### Run FastSchema Binary Source: https://fastschema.com/docs/getting-started Starts the FastSchema application by executing the downloaded binary. This command assumes the binary is present in the current directory. ```bash ./fastschema start ``` -------------------------------- ### Build and Run FastSchema Binary Source: https://fastschema.com/docs/getting-started Commands to compile the FastSchema Go application into an executable binary and then run it. Requires Go 1.18 or later. ```bash go build -o fastschema cmd/main.go ./fastschema start ``` -------------------------------- ### Build FastSchema Dashboard (Optional) Source: https://fastschema.com/docs/getting-started Instructions to build the FastSchema dashboard using Yarn. This step is optional and requires a `.env.production` file in the `./pkg/dash` directory. ```bash cd pkg/dash yarn install && yarn build cd ../../ && mkdir -p private/tmp ``` -------------------------------- ### Clone Repository and Initialize Submodules Source: https://fastschema.com/docs/getting-started Steps to clone the FastSchema repository from GitHub and update its Git submodules. This is the initial step for building from source. ```bash git clone https://github.com/fastschema/fastschema.git cd fastschema git submodule update --init --recursive ``` -------------------------------- ### Create Basic FastSchema App Source: https://fastschema.com/docs/framework A minimal example demonstrating how to initialize a FastSchema application and add a simple GET resource that returns 'Hello World'. ```go package main import ( "github.com/fastschema/fastschema/fs" "github.com/fastschema" ) func main() { app, _ := fastschema.New(&fs.Config{ Port: "8000", }) app.AddResource(fs.Get("/", func(c fs.Context, _ any) (string, error) { return "Hello World", nil })) app.Start() } ``` -------------------------------- ### Pull FastSchema Docker Image Source: https://fastschema.com/docs/getting-started Pulls the latest FastSchema Docker image from the container registry. This is the initial step for installing FastSchema using Docker. ```bash docker pull ghcr.io/fastschema/fastschema:latest ``` -------------------------------- ### FastSchema Configuration Environment Variables Source: https://fastschema.com/docs/getting-started Example of environment variables used for configuring FastSchema, including application port, base URLs, and database connection details. Supports SQLite by default, but can be configured for other databases like MySQL. ```ini APP_KEY=a_32_characters_random_string APP_PORT=8000 APP_BASE_URL=http://localhost:8000 APP_DASH_URL=http://localhost:8000/dash APP_API_BASE_NAME=api DB_DRIVER=mysql DB_NAME=fastschema DB_HOST=127.0.0.1 DB_PORT=3306 DB_USER=root DB_PASS=123 STORAGE='{"default_disk":"public","disks":[{"name":"public","driver":"local","root":"./public","public_path":"/","base_url":"http://localhost:8000/"},{"name":"my_s3","driver":"s3","root":"/files","provider":"DigitalOcean","endpoint":"sfo3.digitaloceanspaces.com","region":"sfo3","bucket":"my_bucket","access_key_id":"s3_access_key_id","secret_access_key":"s3_secret_access_key","base_url":"https://cdn.site.local"}]}' ``` -------------------------------- ### Extract FastSchema Binary Source: https://fastschema.com/docs/getting-started Extracts the FastSchema binary archive downloaded from GitHub Releases. This command is used to unpack the application files for execution. ```bash unzip fastschema_0.6.2_linux_amd64.zip ``` -------------------------------- ### Create and Add Resource to ResourceManager Source: https://fastschema.com/docs/framework/resource Demonstrates how to create a new ResourceManager instance and add a basic 'hello' Resource to it. This example shows the initialization of a resource with a handler and metadata for a GET request at '/'. ```go resourceManager := fs.NewResourcesManager() resourceManager.Add( fs.NewResource("hello", func(c fs.Context, _ any) (string, error) { return "Hello, World!", nil }, &fs.Meta{ Get: "/" }), ) ``` -------------------------------- ### Install FastSchema Source: https://fastschema.com/docs/framework Command to install the FastSchema Go module using the go get command. Ensure you have Go 1.18 or later installed. ```bash go get github.com/fastschema/fastschema ``` -------------------------------- ### Create and Start FastSchema Application (Go) Source: https://fastschema.com/docs/framework/application Demonstrates how to initialize a new FastSchema Application instance with default configurations and start its web server. It includes adding a basic resource handler for the root path. ```go app, err := fastschema.New(&fs.Config{}) if err != nil { log.Fatal(err) } app.AddResource(fs.Get("/", func(c fs.Context, _ any) (string, error) { return "Hello World", nil })) app.Start() ``` -------------------------------- ### Run FastSchema Docker Container Source: https://fastschema.com/docs/getting-started Runs the FastSchema Docker container, mapping port 8000 and mounting a local 'data' directory for persistence. It automatically generates an APP_KEY and uses a default SQLite database. ```bash mkdir data docker run \ -u "$UID" \ -p 8000:8000 \ -v ./data:/fastschema/data \ ghcr.io/fastschema/fastschema:latest ``` -------------------------------- ### FastSchema Minimum Configuration (.env Examples) Source: https://fastschema.com/docs/configuration Provides examples of essential environment variables for FastSchema. It shows the mandatory APP_KEY and demonstrates how to configure different database drivers like MySQL. ```ini APP_KEY=S5BZycqw4ad8NLAjzmE7gMfCTHDJUGWu ``` ```ini APP_KEY=S5BZycqw4ad8NLAjzmE7gMfCTHDJUGWu DB_DRIVER=mysql DB_NAME=fastschema DB_USER=root DB_PASS=secret ``` -------------------------------- ### Create FastSchema Resource Example Source: https://fastschema.com/docs/framework/resource Demonstrates how to define input/output structures and create a new resource with a handler function and metadata using the `fs.NewResource` function in Go. This resource is accessible via a GET request to the root path. ```go package main import ( "github.com/fastwego/fastschema/fs" ) type Input struct { Name string `json:"name"` } type Output struct { Message string `json:"message"` } func main() { handler := func(c fs.Context, input *Input) (*Output, error) { return &Output{ Message: "Hello, " + input.Name, }, nil } meta := &fs.Meta{Get: "/"} rs := fs.NewResource("hello", handler, &fs.Meta{Get: "/"}) } ``` -------------------------------- ### Resource Helper Example (fs.Get) Source: https://fastschema.com/docs/framework/resource/helpers Demonstrates using the fs.Get helper to define a GET endpoint for a resource, specifying the path and the handler function. ```go rs := fs.Get("/path", func(c fs.Context, input *Input) (*Output, error) { return &Output{ Message: "Hello, " + input.Name, }, nil }) ``` -------------------------------- ### Example: Testing an HTTP Handler Source: https://fastschema.com/docs/framework/testing Demonstrates how to set up a schema builder, an in-memory database client, a tool service, and resources, then use the server's Test method to send a request and assert the response. ```go sb, _ := schema.NewBuilderFromDir(t.TempDir(), fs.SystemSchemaTypes...) db, _ := entdbadapter.NewTestClient( utils.Must(os.MkdirTemp("", "migrations")), sb, ) toolService := toolservice.New(&testApp{sb: sb, db: db}) resources := fs.NewResourcesManager() resources.Group("tool"). Add(fs.Get("stats", func(c fs.Context, _ any) (any, error) { return "stats", nil })) assert.NoError(t, resources.Init()) server := restfulresolver.NewRestfulResolver( resources, logger.CreateMockLogger(true), ).Server() req := httptest.NewRequest("GET", "/tool/stats", nil) resp := utils.Must(server.Test(req)) defunc() { assert.NoError(t, resp.Body.Close()) }() assert.Equal(t, 200, resp.StatusCode) response := utils.Must(utils.ReadCloserToString(resp.Body)) assert.Contains(t, response, `stats`) ``` -------------------------------- ### FastSchema Auth Configuration (Go Struct & JSON Example) Source: https://fastschema.com/docs/configuration Defines the Go struct for authentication configuration and provides a JSON example for enabling GitHub and Google providers. It specifies the structure for enabling multiple authentication providers and their respective credentials. ```go type AuthConfig struct { EnabledProviders []string `json:"enabled_providers"` Providers map[string]Map `json:"providers"` } ``` ```json { "enabled_providers": [ "github", "google" ], "providers": { "local": { "activation_method": "email", "activation_url": "http://localhost:3001/activation", "recovery_url": "http://localhost:3001/recover" }, "github": { "client_id": "github_client_id", "client_secret": "github_client_secret" }, "google": { "client_id": "xxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com", "client_secret": "xxx" }, "twitter": { "consumer_key": "twitter_consumer_key", "consumer_secret": "twitter_consumer_secret" } } } ``` -------------------------------- ### JSON Example for Default Disk Configuration Source: https://fastschema.com/docs/framework/storage Provides a sample JSON object illustrating the configuration for a default storage disk. This example shows common settings like driver, root directory, public path, and base URL for a local disk. ```json { "name": "public", "driver": "local", "root": "./public", "public_path": "/files", "base_url": "http://localhost:8000/files" } ``` -------------------------------- ### Local Execution Configuration Example Source: https://fastschema.com/docs/configuration Shows how to configure FastSchema for local execution by setting environment variables directly in the terminal before starting the application. This method is useful for development environments. ```bash APP_KEY=S5BZycqw4ad8NLAjzmE7gMfCTHDJUGWu \ APP_BASE_URL=https://myapp.ltd \ APP_DASH_URL=https://myapp.ltd/dash \ ./fastschema start ``` -------------------------------- ### Application Logger Usage Example Source: https://fastschema.com/docs/framework/logging Illustrates how to obtain the application's logger instance using `app.Logger()` and perform a basic logging operation. This requires initializing a FastSchema application first. ```go app, _ := fastschema.New(&fs.Config{ SystemSchemas: []any{Tag{}, Blog{}}, }) app.Logger().Info("Hello, World!") ``` -------------------------------- ### FastSchema Mail Configuration (Go Struct & JSON Example) Source: https://fastschema.com/docs/configuration Illustrates the Go struct for mail configuration, including sender details and client configurations. A JSON example demonstrates setting up a default sender and configuring an SMTP client for mailtrapsmtp. ```go type MailConfig struct { SenderName string `json:"sender_name"` SenderMail string `json:"sender_mail"` DefaultClientName string `json:"default_client"` Clients []Map `json:"clients"` } ``` ```json { "sender_name": "FastSchema Accounts", "sender_mail": "accounts@fastschema.com", "default_client": "mailtrapsmtp", "clients": [ { "name": "mailtrapsmtp", "driver": "smtp", "host": "sandbox.smtp.mailtrap.io", "port": 2525, "username": "username", "password": "password" } ] } ``` -------------------------------- ### FastSchema Storage Configuration (Go Structs & JSON Example) Source: https://fastschema.com/docs/configuration Details the Go structs for storage configuration, including the main StorageConfig and DiskConfig. It also provides a JSON example for a 'public' disk using the local driver, specifying root path and base URL. ```go type StorageConfig struct { DefaultDisk string `json:"default_disk"` Disks []*DiskConfig `json:"disks"` } ``` ```go // github.com/fastschema/fastschema/fs/fs.go type DiskConfig struct { Name string `json:"name"` Driver string `json:"driver"` Root string `json:"root"` BaseURL string `json:"base_url"` PublicPath string `json:"public_path"` Provider string `json:"provider"` Endpoint string `json:"endpoint"` Region string `json:"region"` Bucket string `json:"bucket"` AccessKeyID string `json:"access_key_id"` SecretAccessKey string `json:"secret_access_key"` ACL string `json:"acl"` GetBaseURL func() string `json:"-"` } ``` ```json [ { "name": "public", "driver": "local", "root": "./public", "public_path": "/files", "base_url": "http://localhost:8000/files" } ] ``` -------------------------------- ### Docker Configuration Example Source: https://fastschema.com/docs/configuration Demonstrates how to run FastSchema using Docker and set essential environment variables for application configuration. This includes setting the application key, base URL, and dashboard URL. ```bash docker run \ -e APP_KEY=S5BZycqw4ad8NLAjzmE7gMfCTHDJUGWu \ -e APP_BASE_URL=https://myapp.ltd \ -e APP_DASH_URL=https://myapp.ltd/dash \ -u "$UID" \ -p 8000:8000 \ -v ./data:/fastschema/data \ ghcr.io/fastschema/fastschema:latest ``` -------------------------------- ### Install FastSchema SDK (Browser) Source: https://fastschema.com/docs/sdk Includes the FastSchema SDK via a script tag for browser environments. After loading, a new FastSchema instance can be created by providing the backend URL. ```html ``` -------------------------------- ### Configure FastSchema Application (Go) Source: https://fastschema.com/docs/framework/application Shows how to customize the FastSchema Application's behavior by providing a specific configuration object during initialization. This example sets the port, base URL, and hides resource information. ```go app, err := fastschema.New(&fs.Config{ Port: "8001", BaseURL: "http://localhost:8001", HideResourcesInfo: true, }) ``` -------------------------------- ### Install FastSchema SDK (NPM) Source: https://fastschema.com/docs/sdk Installs the FastSchema SDK package using npm for use in Node.js or modern JavaScript projects. ```bash npm install fastschema ``` -------------------------------- ### Run FastSchema Binary Source: https://fastschema.com/docs/framework/deployment This command executes the FastSchema standalone binary. It requires the binary to be downloaded and placed in the current directory. The command starts the FastSchema application. ```bash ./fastschema start ``` -------------------------------- ### JSON: Example AuthConfig Structure Source: https://fastschema.com/docs/backend/authentication Provides a concrete example of the AuthConfig structure in JSON format. It demonstrates how to enable 'github' and 'google' providers and configure their respective client IDs and secrets. This JSON is typically minified before being set as the AUTH environment variable. ```json { "enabled_providers": [ "github", "google" ], "providers": { "local": { "activation_method": "email", "activation_url": "http://frontend-site.local/activation", "recovery_url": "http://frontend-site.local/recover" }, "github": { "client_id": "github_client_id", "client_secret": "github_client_secret" }, "google": { "client_id": "xxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com", "client_secret": "xxx" } } } ``` -------------------------------- ### FastSchema Database Transaction Example Source: https://fastschema.com/docs/framework/database/transaction Demonstrates creating a transaction, performing multiple record creations (Tags and Blog), and associating them within the transaction. It shows how to use the Builder with a transaction client. ```go ctx := context.Background() tx, _ := client.Tx(ctx) tag1, _ := db.Builder[Tag](tx).Create(ctx, fs.Map{ "name": "Tag 1", "desc": "Tag 1 description", }) tag2, _ := db.Builder[Tag](tx).Create(ctx, fs.Map{ "name": "Tag 2", "desc": "Tag 2 description", }) blog, err := db.Builder[Blog](tx).Create(ctx, fs.Map{ "title": "Hello World", "body": "This is a blog post", "tags": []*schema.Entity{ schema.NewEntity(tag1.ID), schema.NewEntity(tag2.ID), }, }) tx.Commit() // tx.Rollback() ``` -------------------------------- ### Create Public Resource Source: https://fastschema.com/docs/framework Example of adding a resource that does not require authentication by setting the 'Public' field to true in its metadata. ```go app.AddResource(fs.Get("/", func(c fs.Context, _ any) (string, error) { return "Hello World", nil }, &fs.Meta{Public: true})) ``` -------------------------------- ### Go Database Query Example Source: https://fastschema.com/docs/framework/database/query Demonstrates building a database query using the FastSchema query builder. It includes selecting specific fields, applying filters with OR conditions, ordering results, and setting limits and offsets. ```go // blogs has type []Blog blogs, err := db.Builder[Blog](client). Select("id", "title", "tags.id", "tags.name"). Where(db.Or( db.EQ("id", 1), db.EQ("title", "First Blog"), )). Order("-id"). Limit(10). Offset(20). Get(context.Background()) ``` -------------------------------- ### Configure Query Parameters (Args) for FastSchema Resource Source: https://fastschema.com/docs/framework/resource/meta Defines the query parameters a resource accepts. Each parameter is specified with its type, whether it's required, a description, and an example value. ```go meta := &fs.Meta{ Get: "/search", Args: fs.Args{ "search": fs.Arg{ Type: fs.TypeString, Required: true, Description: "Search query", Example: "Hello", }, "limit": fs.Arg{ Type: fs.TypeInt, Description: "Limit the number of items to return", Example: 10, }, }, } ``` -------------------------------- ### Go Query Example with Struct Source: https://fastschema.com/docs/framework/database/raw-sql Demonstrates how to use the `Query` function with a specific struct type (`Blog`) to retrieve and scan data. The generic type parameter `[Blog]` specifies the expected result structure. ```go // blogs has the type []Blog blogs, err := db.Query[Blog]( ctx, client, "SELECT * FROM blogs WHERE id > ?", 1, ) ``` -------------------------------- ### Go Query Example with schema.Entity Source: https://fastschema.com/docs/framework/database/raw-sql Demonstrates how to use the `Query` function with `*schema.Entity` to scan results when a specific struct is not defined or desired. This is useful for flexible data retrieval. ```go // blogs has the type []*schema.Entity blogs, err := db.Query[*schema.Entity]( ctx, client, "SELECT * FROM blogs WHERE id > ?", 1, ) ``` -------------------------------- ### Create Restful Resolver Source: https://fastschema.com/docs/framework/resource/resolver Demonstrates how to create a new RestfulResolver. It requires a ResourceManager and a Logger, and optionally accepts StaticFs for serving static files. The resolver sets up routes based on resources and starts a web server. ```go func NewRestResolver( resourceManager *fs.ResourcesManager, logger logger.Logger, staticFSs ...*fs.StaticFs, ) *RestSolver ``` -------------------------------- ### FastSchema Plugin Configuration and Resource Setup Source: https://fastschema.com/docs/plugins This JavaScript snippet demonstrates how to configure a FastSchema plugin. It shows how to add schemas, set the port, and define public resources (routes) within a plugin group. ```js const product = require('./schemas/product.json'); const { getRandomName, ping } = require('./utils'); const Config = config => { // Add product schema config.AddSchemas(product); // Change the fastschema port to 9000 config.port = '9000'; } const Init = plugin => { // Create a group named 'hello' with two public resources (routes): // - hello/ping // - hello/world plugin.resources .Group('hello') .Add(ping, { public: true }) .Add(world, { public: true }); } const world = async ctx => { const name = await getRandomName(); return `Hello, ${name}!`; } ``` -------------------------------- ### Go System Schema Query Builder Example Source: https://fastschema.com/docs/framework/database/query Illustrates how to create a query builder specifically for a system schema in Go. It shows passing the `Blog` struct type to `db.Builder` to query the `blog` table. ```go // Create a query builder to query from the table `blog` // Blog is a SystemSchema query := db.Builder[Blog](client) ``` -------------------------------- ### Creating a New Storage Disk Instance Source: https://fastschema.com/docs/framework/storage Demonstrates how to initialize a new storage disk instance using `rclonefs.NewFromConfig`. This function takes a slice of `DiskConfig` pointers and a local root path to set up the disk drivers. ```go disks, err = rclonefs.NewFromConfig( storageDisksConfig, // []*DiskConfig localRoot, // string representing the local root path ) ``` -------------------------------- ### FastSchema API Filtering Example with $neq Issue Source: https://fastschema.com/docs/backend/list-records Demonstrates an HTTP GET request to filter posts by tags using the $neq operator. This example highlights a known issue where filtering on m2m relation fields with $neq might not produce the expected results due to incorrect SQL query generation. ```http GET http://localhost:8000/api/content/post?select=id \ &filter={"tags.id":{"$neq":10001}} ``` ```sql SELECT * FROM `posts` WHERE `posts`.`id` IN ( SELECT `posts_tags`.`posts` FROM `posts_tags` JOIN `tags` AS `t1` ON `posts_tags`.`tags` = `t1`.`id` WHERE `id` <> 10001 ) ORDER BY `id` DESC ``` ```sql SELECT * FROM `posts` WHERE `posts`.`id` NOT IN ( SELECT `posts_tags`.`posts` FROM `posts_tags` JOIN `tags` AS `t1` ON `posts_tags`.`tags` = `t1`.`id` WHERE `id` = 10001 ) ORDER BY `id` DESC ``` -------------------------------- ### FastSchema WithTx Execution Example Source: https://fastschema.com/docs/framework/database/transaction Illustrates the usage of the WithTx helper function to execute a block of database operations atomically. This example creates tags and a blog post, ensuring atomicity. ```go err := db.WithTx(client, context.Background(), func(tx db.Client) error { tag1, _ := db.Builder[Tag](tx).Create(ctx, fs.Map{ "name": "Tag 1", "desc": "Tag 1 description", }) tag2, _ := db.Builder[Tag](tx).Create(ctx, fs.Map{ "name": "Tag 2", "desc": "Tag 2 description", }) blog, err := db.Builder[Blog](tx).Create(ctx, fs.Map{ "title": "Hello World", "body": "This is a blog post", "tags": []*schema.Entity{ schema.NewEntity(tag1.ID), schema.NewEntity(tag2.ID), }, }) return err }) ``` -------------------------------- ### Go: Initialize Ent Client with Migrations Source: https://fastschema.com/docs/framework/database/migrations Demonstrates how to initialize an Ent database client for FastSchema. It involves creating a schema builder from a directory, configuring the database connection (driver, name, host, credentials), and specifying the migration directory for schema changes. ```go sb, _ := schema.NewBuilderFromDir("data/schemas", Blog{}, Tag{}) config := &db.Config{ Driver: "mysql", Name: "fastschema2", Host: "localhost", Port: "3306", User: "root", Pass: "123", DisableForeignKeys: true, MigrationDir: "data/migrations", } client, _ := entdbadapter.NewClient(config, sb) ``` -------------------------------- ### Execute Query and Get All Records (Go) Source: https://fastschema.com/docs/framework/database/query The Get method executes the constructed query and returns a slice of records that match the criteria. It requires a context and returns the records along with any potential error. ```go query := db.Builder[Blog](client) // records has type []*Blog records, err := query.Get(context.Background()) ``` ```go query := db.Builder(client, schema.NamedEntity("blog")) // records has type []*schema.Entity records, err := query.Get(context.Background()) ``` -------------------------------- ### Example Mail Configuration (JSON) Source: https://fastschema.com/docs/framework/mail An example JSON configuration for the mail system, setting a sender name and email, specifying a default client named 'mailtrapsmtp', and defining the 'smtp' driver client with host, port, username, and password. ```json { "sender_name": "FastSchema Accounts", "sender_mail": "accounts@fastschema.com", "default_client": "mailtrapsmtp", "clients": [ { "name": "mailtrapsmtp", "driver": "smtp", "host": "sandbox.smtp.mailtrap.io", "port": 2525, "username": "username", "password": "password" } ] } ``` -------------------------------- ### Initialize and Authenticate FastSchema SDK Source: https://fastschema.com/docs/sdk Demonstrates how to create a FastSchema instance, log in with credentials, and initialize the SDK. Initialization must be performed before any other operations. ```typescript import { FastSchema } from "fastschema"; // Create a new instance of FastSchema const fs = new FastSchema("http://localhost:8000"); // Login await fs.auth().login({ login: "admin", password: "123", }); // Initialize: This must be called before any other operation await fs.init(); ``` -------------------------------- ### Direct Database Client Creation Source: https://fastschema.com/docs/framework/database Illustrates creating a database client directly using the `entdbadapter` package. This method requires passing a `db.Config` object and a pre-initialized schema builder. It's suitable for scenarios where the client is managed manually. ```go schemaDir := "data/schemas" migrationDir := "data/migrations" builder, err := schema.NewBuilderFromDir(schemaDir, Blog{}, Tag{}) if err != nil { log.Fatal(err) } config := &db.Config{ Driver: "mysql", Name: "fastschema2", Host: "localhost", Port: "3306", User: "root", Pass: "123", MigrationDir: migrationDir, } client, err := entdbadapter.NewClient(config, builder) if err != nil { log.Fatal(err) } ``` -------------------------------- ### FastSchema Plugin Init Function Source: https://fastschema.com/docs/plugins/initialization Demonstrates the `Init` function for plugin initialization. It shows how to use logger, perform database queries, and register resources using the `plugin.resources` object. Includes the `FsPlugin` interface definition. ```js const ping = ctx => { return 'pong'; }; const world = ctx => { return 'Hello World'; }; /** @param {FsPlugin} plugin */ const Init = plugin => { $logger().Info('Hello plugin is initializing...'); const products = $db().Query($context(), 'SELECT * FROM products'); $logger().Info('Products:', products); plugin.resources .Group('hello') .Add(ping, { public: true }) .Add(world, { public: true }); }; ``` ```ts export interface FsPlugin { name: string; resources: FsResource; } ``` -------------------------------- ### Get a Schema using FastSchema SDK Source: https://fastschema.com/docs/sdk Retrieves a specific schema by its name. This operation will throw an error if the schema does not exist. ```typescript const schemaTag = fs.schema("tag"); ``` -------------------------------- ### Define Resource Prefix in FastSchema Source: https://fastschema.com/docs/framework/resource/meta Specifies a URL prefix under which a resource should be registered. This allows for organizing API endpoints, for example, by version or module. ```go meta := &fs.Meta{ Prefix: "/api/v1", } ``` -------------------------------- ### FastSchema Plugin Config Function Example Source: https://fastschema.com/docs/plugins/configuration Demonstrates defining a `Config` function within a plugin to modify FastSchema settings, such as changing the port and adding schemas. ```js const Config = config => { // Add product schema config.AddSchemas(product); // Change the fastschema port to 9000 config.port = '9000'; } ``` -------------------------------- ### Execute Query and Get First Record (Go) Source: https://fastschema.com/docs/framework/database/query The First method executes the query and returns only the first record that matches the criteria. It returns an error if no record is found. ```go query := db.Builder[Blog](client) // record has type *Blog record, err := query.First(context.Background()) ``` ```go query := db.Builder(client, schema.NamedEntity("blog")) // record has type *schema.Entity record, err := query.First(context.Background()) ``` -------------------------------- ### Create Mock Database Adapter Source: https://fastschema.com/docs/framework/testing A helper function to create a mock adapter for the database. It simulates database interactions using sqlmock, useful for testing generated SQL queries. ```go mockAdapter := db.CreateMockAdapter() ``` -------------------------------- ### Database Client via FastSchema Application Source: https://fastschema.com/docs/framework/database Shows how to obtain a database client automatically when creating a new `fastschema` application. The client is accessible via the `app.DB()` method, simplifying integration. Configuration can be provided via `DBConfig` or environment variables. ```go app, err := fastschema.New(&fs.Config{ SystemSchemas: []any{Tag{}, Blog{}}, DBConfig: &db.Config{ Driver: "mysql", Name: "fastschema", Host: "localhost", Port: "3306", User: "root", Pass: "123", MigrationDir: migrationDir, }, }) if err != nil { log.Fatal(err) } client := app.DB() ``` -------------------------------- ### Foreign Key Column Override Example Source: https://fastschema.com/docs/concepts Demonstrates how to override the default foreign key column name using the `fk_columns` configuration. The default is typically `related_schema_id`, but this allows customization. ```json { "target_column": "cat_id" } ``` -------------------------------- ### Create Record API Request Body Source: https://fastschema.com/docs/backend/create-record Provides an example of the JSON payload for creating a record. It shows how to include simple fields and nested objects for relations. ```json { "name": "Example Post", "priority": 1, "category": { "id": 2 }, "tags": [{ "id": 2 }, { "id": 3 }] } ``` -------------------------------- ### Create Test Database Client Source: https://fastschema.com/docs/framework/testing Creates a new test client using an in-memory SQLite database. This allows testing database client behavior without connecting to a real database. ```go testClient := db.NewTestClient() ```