### Quickstart Arri RPC Project Setup Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-server/README.md Commands to quickly initialize, navigate, install dependencies, and run an Arri RPC project using either npm or pnpm. ```bash # npm npx arri init [project-name] cd [project-name] npm install npm run dev # pnpm pnpm dlx arri init [project-name] cd [project-name] pnpm install pnpm run dev ``` -------------------------------- ### Start Arri RPC Integration Test Server Source: https://github.com/modiimedia/arri/blob/master/CONTRIBUTING.md Commands to start the integration test server for Arri RPC. It first ensures code generators are up-to-date and then allows starting either the TypeScript or Go test server to facilitate client-side integration testing. ```Bash # ensure your code generators are the most recent build pnpm build # start either the TS or Go test server pnpm nx dev test-server-ts pnpm nx dev test-server-go ``` -------------------------------- ### Arri Language-Specific Project Structure Example Source: https://github.com/modiimedia/arri/blob/master/CONTRIBUTING.md Shows an example of how language-specific projects are organized within the 'languages' directory, using Python as an illustration for client, codegen, and server components. ```fs |- languages |- python |- python-client |- python-codegen |- python-codegen-reference |- python-server ``` -------------------------------- ### Start Arri RPC Playground Development Server Source: https://github.com/modiimedia/arri/blob/master/CONTRIBUTING.md Commands to start the development server for the Arri RPC playground, allowing developers to experiment with either the TypeScript or Go server playgrounds without affecting the main project. ```Bash # spin up the Typescript server playground pnpm nx dev ts-playground # spin up the Go server playground pnpm nx dev go-playground ``` -------------------------------- ### Example Arri GET Request URL with Query Parameters Source: https://github.com/modiimedia/arri/blob/master/docs/implementing-an-arri-server.md Illustrates how parameters for an Arri GET request are appended to the URL as query parameters. This example shows a base URL with multiple key-value pairs representing the RPC parameters. ```txt http://myapi.com/users/get-user?a=FOO&b=BAR&c=BAZ ``` -------------------------------- ### Example NX Project Configuration File Source: https://github.com/modiimedia/arri/blob/master/CONTRIBUTING.md Illustrates a basic `project.json` file used by NX to define project-specific targets. This example shows a custom 'foo' target that executes a simple shell command within the project's directory. ```JSON { "name": "my-awesome-project", "schemaPath": "../../path-to/node_modules/nx/schemas/project-schema.json", "targets": { "foo": { "executor": "nx:run-commands", "options": { "command": "echo 'foo'", "cwd": "path/to/my-awesome-project" } } } } ``` -------------------------------- ### Install Dependencies and Build TypeScript Projects Source: https://github.com/modiimedia/arri/blob/master/CONTRIBUTING.md Installs project dependencies using pnpm and then builds all TypeScript projects in the repository. This is a prerequisite for working on code generators and other TypeScript-based components. ```Bash pnpm i pnpm build ``` -------------------------------- ### Basic Arri Go Server Application Source: https://github.com/modiimedia/arri/blob/master/languages/go/go-server/README.md This example demonstrates a complete Arri RPC Go server. It defines a custom event type (`MyCustomEvent`), initializes an Arri application with a custom event creator, registers two RPC procedures (`SayHello`, `SayGoodbye`), and starts the server on port 3000. It also illustrates the required struct definitions for RPC parameters and responses. ```go package main import ( "log" "net/http" "github.com/modiimedia/arri" ) // this is the type that will be passed around to every procedure // it must implement the `arri.Event` interface // if you don't want to define a custom event you can use `arri.DefaultEvent` and `arri.CreateDefaultEvent()` instead type MyCustomEvent struct { r *http.Request w http.ResponseWriter } func (e MyCustomEvent) Request() *http.Request { return e.r } func (e MyCustomEvent) Writer() http.ResponseWriter { return e.w } func main() { // creates a CLI app that accepts parameters for outputting an Arri app definition app := arri.NewApp( http.DefaultServeMux, arri.AppOptions[MyCustomEvent]{}, // function to create your custom Event type using the incoming request func(w http.ResponseWriter, r *http.Request) (*MyCustomEvent, arri.RpcError) { return &MyCustomEvent{ r: r, w: w, }, nil }, ) // register procedures arri.Rpc(&app, SayHello, arri.RpcOptions{}) arri.Rpc(&app, SayGoodbye, arri.RpcOptions{}) // run the app on port 3000 // It's err := app.Run(arri.RunOptions{Port: 3000}) if err != nil { log.Fatal(err) return } } // Procedure inputs and outputs must be structs type GreetingParams struct { Name string } type GreetingResponse struct { Message string } // RPCs take two inputs and have two outputs // // Inputs: // The first input will be registered as the RPC params. This is what clients will send to the server. // The second input will be whatever type you have defined to be the Event type. In this case it's "MyCustomEvent" // // Outputs: // The first output will be the OK response sent back to the client // The second output will be the Error response sent back to the client func SayHello(params GreetingParams, event MyCustomEvent) (GreetingResponse, arri.RpcError) { return GreetingResponse{ Message: "Hello " + params.Name }, nil } func SayGoodbye(params GreetingParams, event MyCustomEvent) (GreetingResponse, arri.RpcError) { return GreetingResponse{ Message: "Goodbye " + params.Name }, nil } ``` -------------------------------- ### Execute NX Commands for Project Management Source: https://github.com/modiimedia/arri/blob/master/CONTRIBUTING.md Demonstrates the basic usage of the NX command-line tool for orchestrating builds and running tests across different projects. Examples include building a TypeScript server, compiling a Rust client, and testing a Dart code generator. ```Bash # basic usage pnpm nx [target] [project-name] # examples pnpm nx build ts-server pnpm nx compile rust-client pnpm nx test dart-codegen # Sidenote: # If you choose to install NX globally you can omit the `pnpm` prefix ``` -------------------------------- ### TypeScript Configuration for Arri Go Server Plugin Source: https://github.com/modiimedia/arri/blob/master/docs/implementing-an-arri-server.md This TypeScript snippet defines an Arri server configuration (`goServer`) that integrates a Go application's development and build processes. The `devFn` handles running `go generate`, reading the `AppDefinition`, executing Arri generators, and starting the Go application. The `buildFn` performs similar steps but concludes with `go build` instead of `go run`, ensuring the Go application is compiled. This setup streamlines the `arri dev` and `arri build` commands for Go projects. ```TypeScript const goServer = defineServerConfig({ devArgs: {}, devFn(_, generators) { // run "go generate" execSync("go generate", { stdio: "inherit" }); // read the App Definition const appDef = JSON.parse( readFileSync(".arri/__definition.json", "utf8") ) as AppDefinition; // run all of the registered Arri generators await Promise.all(generators.map((item) => item.generator(appDef))); // start the go application execSync("go run main.go", { stdio: 'inherit' }); }, buildArgs: {}, buildFn(_, generators) { // run "go generate" execSync("go generate", { stdio: "inherit" }); // read the App Definition const appDef = JSON.parse( readFileSync(".arri/__definition.json", "utf8") ) as AppDefinition; // run all of the registered Arri generators await Promise.all(generators.map((item) => item.generator(appDef))); // run "go build" execSync("go build", { stdio: "inherit" }); } }); export default defineConfig({ server: goServer, generators: [...] }) ``` -------------------------------- ### Install Arri-RPC ESLint Plugin Source: https://github.com/modiimedia/arri/blob/master/languages/ts/eslint-plugin/README.md Instructions for installing the @arrirpc/eslint-plugin package as a development dependency using npm or pnpm. ```bash # npm npm i --save-dev @arrirpc/eslint-plugin # pnpm pnpm i --save-dev @arrirpc/eslint-plugin ``` -------------------------------- ### Install Arri RPC Typebox Adapter Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-schema-typebox-adapter/README.md Instructions for installing the @arrirpc/typebox-adapter package using popular Node.js package managers. ```bash npm install @arrirpc/typebox-adapter ``` ```bash pnpm install @arrirpc/typebox-adapter ``` -------------------------------- ### Arri Procedure Definition for GET Request Source: https://github.com/modiimedia/arri/blob/master/docs/implementing-an-arri-server.md Example of an Arri procedure definition in JSON, illustrating a GET request where parameters are passed as URL query parameters. It specifies the transport, method, path, parameters, and response types. ```json { "users.getUser": { "transport": "http", "method": "get", "path": "/users/get-user", "params": "GetUserParams", "response": "User" } } ``` -------------------------------- ### Scaffolding a New Arri Project Source: https://github.com/modiimedia/arri/blob/master/CONTRIBUTING.md Command to run the project scaffolding script, which assists in setting up 'code-generator' or 'tooling' projects within Arri. ```bash pnpm scaffold ``` -------------------------------- ### Run Single Language Integration Tests Source: https://github.com/modiimedia/arri/blob/master/CONTRIBUTING.md Executes integration tests for a specific client language after the test server has been started. Replace `{{language}}` with the desired client language (e.g., `rust`, `dart`, `go`, `swift`) to target specific client implementations. ```Bash pnpm nx integration-test test-client-{{language}} ``` -------------------------------- ### Initialize Arri Go Project with CLI Source: https://github.com/modiimedia/arri/blob/master/languages/go/go-server/README.md Use the Arri CLI to scaffold a new Go server project. This command initializes the project, navigates into its directory, and installs dependencies using either npm or pnpm. It also shows the interactive prompt for language selection during initialization. ```bash npx arri init [project-name] cd [project-name] npm install npm run dev ``` ```bash pnpm dlx arri init [project-name] cd [project-name] pnpm install pnpm run dev ``` ```terminal What kind of project do you want to initialize? -> application generator plugin What language do you want to use? typescript -> go ``` -------------------------------- ### Install Arri RPC Dependencies Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-server/README.md Commands to install core Arri RPC server and schema dependencies, along with the Arri CLI, using npm or pnpm. ```bash # npm npm install -D arri npm install @arrirpc/server @arrirpc/schema # pnpm pnpm install -D arri pnpm install @arrirpc/server @arrirpc/schema ``` -------------------------------- ### Manually Starting an Arri Server (H3 App) Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-server/README.md An Arri server is fundamentally an H3 application, allowing it to be started manually using Node.js's `http.createServer` and `toNodeListener`. This provides flexibility for custom server setups, though the file-based router currently requires the Arri CLI for full functionality. ```ts import { createServer } from 'node:http'; import { ArriApp, toNodeListener } from '@arrirpc/server'; const app = new ArriApp(); createServer(toNodeListener(app.h3App)).listen(process.env.PORT || 3000); ``` -------------------------------- ### Install Arri Schema Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-schema/README.md Instructions for installing the `@arrirpc/schema` package, which provides the core schema definition and validation functionalities, using either npm or pnpm. ```bash # npm npm install @arrirpc/schema # pnpm pnpm install @arrirpc/schema ``` -------------------------------- ### Install Arri CLI for Code Generation Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-schema/README.md Instructions for installing the `arri` command-line interface tool as a development dependency using npm or pnpm. The Arri CLI is essential for compiling Arri schemas into client code for various programming languages. ```bash # npm npm i --save-dev arri # pnpm pnpm i --save-dev arri ``` -------------------------------- ### Arri Top-Level Project Directory Structure Source: https://github.com/modiimedia/arri/blob/master/CONTRIBUTING.md Illustrates the main directories within the Arri project, categorizing code by language, universal tooling, tests, and internal development scripts. ```fs |- languages // where all of the language specific code codes |- tooling // universal Arri RPC tooling like the CLI |- tests // integration tests and test files |- internal // misc scripts used internally for local development ``` -------------------------------- ### Initialize Specific Arri Rust Client Service Source: https://github.com/modiimedia/arri/blob/master/languages/rust/rust-codegen/README.md This example demonstrates how to initialize a specific sub-service of the generated Arri client, such as `MyClientUsersService`, if only that particular service is needed. ```rust let users_service = MyClientUsersService(config); users_service.some_procedure().await; ``` -------------------------------- ### Working with arri.Option for Optional Values in Go Source: https://github.com/modiimedia/arri/blob/master/languages/go/go-server/README.md This snippet provides practical examples for initializing and manipulating `arri.Option` types in Go. It covers methods for setting, unsetting, unwrapping values, and checking the presence of a value, demonstrating how to handle optional fields programmatically. ```go // initializing options optionalString := arri.Some("hello world") // initialize optional with value optionalString := arri.None[string]() // initialize optional with no value // working with options optionalString.Unwrap() // extract the inner value. panics if there is no value optionalString.UnwrapOr("some-fallback") // extract the inner value if it exist. otherwise use the fallback optionalString.IsSome() // returns true if inner value has been set optionalString.IsNone() // returns true if inner value has not been set optionalString.Set("hello world again") // update the inner value optionalString.Unset() // unset the inner value ``` ```go type Option[T] interface { Unwrap() T bool Set(val T) Unset() } ``` -------------------------------- ### Example Arri App Definition (JSON) Source: https://github.com/modiimedia/arri/blob/master/README.md A complete example of an Arri app definition in JSON format, detailing procedures and data model definitions. This format is typically automatically generated by an ARRI-RPC implementation and is more terse and prone to human error if created manually compared to the TypeScript alternative. ```json { "schemaVersion": "", "procedures": { "sayHello": { "transport": "http", "method": "get", "path": "/say-hello", "params": "HelloParams", "response": "HelloResponse" } }, "definitions": { "HelloParams": { "properties": { "message": { "type": "string", "metadata": {} } }, "metadata": { "id": "HelloParams", "metadata": {} } }, "HelloResponse": { "properties": { "message": { "type": "string", "metadata": {} } }, "metadata": { "id": "HelloResponse" } } } } ``` -------------------------------- ### Install Arri TypeScript Client Library Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-codegen/README.md This snippet provides commands to install the `@arrirpc/client` library using npm or pnpm. It emphasizes that the client library version should match the arri CLI version for compatibility. ```bash # npm npm i @arrirpc/client # pnpm pnpm i --save @arrirpc/client ``` -------------------------------- ### Example Arri Definitions Object for User Types Source: https://github.com/modiimedia/arri/blob/master/specifications/arri_app_definition.md Illustrates the structure of an Arri Definitions object, demonstrating how to define custom data types like 'UserParams' and 'User' with their respective properties and optional metadata for code generation. ```JSON { "UserParams": { "properties": { "userId": { "type": "string" } } }, "User": { "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "isAdmin": { "type": "boolean" } }, "metadata": { "id": "User" } } } ``` -------------------------------- ### Install Arri Dart Client Library Dependency Source: https://github.com/modiimedia/arri/blob/master/languages/dart/dart-codegen/README.md This command installs the `arri_client` Dart library, which is a crucial dependency for the generated Dart code to function correctly. It's important to ensure the installed version matches your Arri CLI version for compatibility. ```Bash dart pub add arri_client ``` -------------------------------- ### Working with arri.Nullable for Nullable Values in Go Source: https://github.com/modiimedia/arri/blob/master/languages/go/go-server/README.md This snippet demonstrates how to initialize and interact with `arri.Nullable` types in Go. It covers methods for setting, unsetting, unwrapping values, checking for nullability, and providing fallback values, offering a comprehensive guide to managing nullable fields. ```go // initializing nullable types nullableString := arri.NotNull("hello world") // initialize nullable with value nullableString := arri.Null[string]() // initialize nullable without value // working with nullables nullableString.Unwrap() // extract the inner value. panics if not set nullableString.UnwrapOr("some-fallback") // extract the inner value if it exists. if it doesn't exists return the fallback nullableString.IsNull() // returns true if null nullableString.Set("hello world again") // update the inner value nullableString.Unset() // unset the inner value ``` -------------------------------- ### Initialize Arri Kotlin Client with Ktor HttpClient Source: https://github.com/modiimedia/arri/blob/master/languages/kotlin/kotlin-codegen/README.md This Kotlin example shows how to initialize the generated Arri client using a Ktor `HttpClient`. It demonstrates setting the base URL and providing a function for dynamic headers, and then calling a procedure. ```kotlin fun main() { // create a Ktor HTTP client val httpClient = HttpClient() { install(HttpTimeout) } // initialize your generated client and pass it the httpClient // the client name will match whatever options you passed into your arri config val client = MyClient( httpClient = httpClient, baseUrl = "https://example.com", // a function that returns a mutable map of headers // this function will run before every request. Or before every reconnection in the case of SSE headers = { mutableMapOf(Pair("x-example-header", "")) } ) runBlocking { client.someProcedure() } } ``` -------------------------------- ### Example Generated Client Models from Arri Schemas Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-schema/README.md These snippets illustrate the client-side data models automatically generated by the Arri CLI from the 'User' schema defined in TypeScript. Examples are provided for Dart, Rust, and Kotlin, showcasing how Arri translates schema definitions into native language constructs. ```dart // dart output class User { final String id; final String? name; final String? email; /// when the user was created final DateTime createdAt; final DateTime updatedAt; const User({ required this.id, this.name, required this.email, required this.createdAt, required this.updatedAt, }); // implementation details } ``` ```rust // rust output pub struct User { id: String, name: String, name: Option, email: Option, // when the user was created created_at: DateTime, updated_at: DateTime, } impl ArriModel for User { // implementation details } ``` ```kotlin // kotlin output data class User( val id: String, val name: String?, val email: String? = null, /** * When the user was created */ val createdAt: Instant, val updatedAt: Instance ) { // implementation details } ``` -------------------------------- ### Configure Arri-RPC ESLint Plugin with Flat File Premade Configs Source: https://github.com/modiimedia/arri/blob/master/languages/ts/eslint-plugin/README.md Examples of using the `arri.recommended` and `arri.all` premade configurations in an `eslint.config.js` flat file for Arri-RPC schema linting. The `recommended` config enables rules related to schema building and codegen, while `all` also includes the `prefer-modular-imports` rule. ```javascript // eslint.config.js import arri from '@arrirpc/eslint-plugin/configs'; // turn on lint rules related to schema building and codegen export default [ arri.recommended, { files: ['src/**/*.ts'], }, ]; // turn on all arri lint rules export default [ arri.all, { files: ['src/**/*.ts'] } ] ``` -------------------------------- ### Empty JSON Object Example Source: https://github.com/modiimedia/arri/blob/master/tests/test-files/README.md Demonstrates a basic empty JSON object, often used as a placeholder or for representing a resource with no properties. ```json {} ``` -------------------------------- ### JSON Object with All Types and Reversed Record Order Source: https://github.com/modiimedia/arri/blob/master/tests/test-files/README.md Similar to the 'ObjectWithEveryType' example, this JSON object demonstrates all supported data types, specifically highlighting a record field where the key-value pairs are in a reversed order compared to the standard example. ```json { "string": "", "boolean": false, "timestamp": "2001-01-01T16:00:00.000Z", "float32": 1.5, "float64": 1.5, "int8": 1, "uint8": 1, "int16": 10, "uint16": 10, "int32": 100, "uint32": 100, "int64": "1000", "uint64": "1000", "enum": "BAZ", "object": { "id": "1", "content": "hello world" }, "array": [true, false, false], "record": { "B": false, "A": true }, "discriminator": { "typeName": "C", "id": "", "name": "", "date": "2001-01-01T16:00:00.000Z" }, "any": "hello world" } ``` -------------------------------- ### Execute Arri CLI Commands with Custom Plugin Arguments Source: https://github.com/modiimedia/arri/blob/master/docs/implementing-an-arri-server.md This example demonstrates how to invoke the `arri dev` and `arri build` commands, passing the custom arguments (`--foo`, `--bar`) that were defined in the server plugin. The plugin's `devFn` and `buildFn` will then receive and process these arguments. ```bash arri dev --foo "hello world" # outputs "hello world" arri build --bar # outputs false ``` -------------------------------- ### Configure Arri Client Generators Source: https://github.com/modiimedia/arri/blob/master/README.md Example `arri.config.ts` file showing how to define various client generators (Dart, Kotlin, TypeScript) for the Arri CLI. This configuration dictates which client SDKs are generated when `arri codegen` is run. ```typescript // arri.config.ts import { defineConfig, generators } from 'arri'; export default defineConfig({ generators: [ generators.dartClient({ // options }), generators.kotlinClient({ // options }), generators.typescriptClient({ // options }) ] }); ``` -------------------------------- ### Complete Arri RPC Server Schema Example Source: https://github.com/modiimedia/arri/blob/master/specifications/arri_app_definition.md This JSON snippet illustrates a full Arri RPC server schema. It defines an 'info' section for metadata, 'procedures' for various RPC calls (e.g., 'users.getUser', 'users.createUser', 'users.watchUser') with their transport, method, path, parameters, and response types. It also includes 'definitions' for complex data types like 'User' and parameter objects, showcasing properties, enums, and timestamps. ```json { "schemaVersion": "0.0.7", "info": { "name": "My Arri Server", "description": "This is a server I made using Arri RPC", "version": "12" }, "procedures": { "users.getUser": { "transport": "http", "method": "get", "path": "/users/get-user", "params": "GetUserParams", "response": "User" }, "users.createUser": { "transport": "http", "method": "post", "path": "/users/create-user", "params": "CreateUserParams", "response": "User" }, "users.watchUser": { "transport": "http", "method": "post", "path": "/users/watch-user", "params": "WatchUserParams", "response": "User", "isEventStream": true } }, "definitions": { "User": { "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "createdAt": { "type": "timestamp" }, "role": { "enum": ["STANDARD", "ADMIN", "MODERATOR"], "metadata": { "id": "UserRole" } } } }, "GetUserParams": { "properties": { "userId": { "type": "string" } } }, "CreateUserParams": { "properties": { "name": { "type": "string" } }, "optionalProperties": { "role": { "enum": ["STANDARD", "ADMIN", "MODERATOR"], "metadata": { "id": "UserRole" } } } }, "WatchUserParams": { "properties": { "userId": { "type": "string" } } } } } ``` -------------------------------- ### Install Arri Rust Client Library Source: https://github.com/modiimedia/arri/blob/master/languages/rust/rust-codegen/README.md This command adds the `arri_client` library as a dependency to your Rust project, which is required for the generated client code to function. Ensure the version matches your Arri CLI version. ```bash cargo add arri_client ``` -------------------------------- ### Global pnpm Commands for Project Operations Source: https://github.com/modiimedia/arri/blob/master/CONTRIBUTING.md Lists common pnpm scripts that execute targets across many projects, including building TypeScript projects, compiling non-TypeScript projects, running unit and integration tests, linting, and type-checking. ```Bash pnpm build pnpm compile pnpm test pnpm integration-tests pnpm lint pnpm typecheck ``` -------------------------------- ### Initialize Arri Dart Client Instance Source: https://github.com/modiimedia/arri/blob/master/languages/dart/dart-codegen/README.md This example demonstrates how to initialize the main generated Dart client class, `MyClient`, by providing a `baseUrl` and an optional asynchronous `headers` function. This client instance provides access to all defined services and procedures. ```Dart // this will match whatever you put in the arri config import "./my_client.g.dart"; main() async { final client = MyClient( baseUrl: "https://example.com", headers: () async { return { "Authorization": "", }; }, ); await client.myProcedure(); } ``` -------------------------------- ### Define Arri RPC Server Configuration Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-server/README.md Example `arri.config.ts` file demonstrating how to define the Arri server and configure client generators for TypeScript and Dart. ```typescript // arri.config.ts import { defineConfig, servers, generators } from 'arri'; export default defineConfig({ server: servers.tsServer(), generators: [ generators.typescriptClient({ // options }), generators.dartClient({ // options }) ] }); ``` -------------------------------- ### Create Arri App Definition with Procedures (TypeScript) Source: https://github.com/modiimedia/arri/blob/master/README.md Example of a TypeScript-based Arri app definition file (`AppDefinition.ts`) that defines RPC procedures (`sayHello`), including parameter and response schemas using `@arrirpc/schema`. This approach leverages Arri's helpers to reduce boilerplate and integrate validators. ```typescript // AppDefinition.ts import { createAppDefinition } from 'arri'; import { a } from '@arrirpc/schema'; const HelloParams = a.object('HelloParams', { message: a.string() }); const HelloResponse = a.object('HelloResponse', { message: a.string() }); export default createAppDefinition({ procedures: { sayHello: { transport: 'http', method: 'post', path: '/say-hello', params: HelloParams, response: HelloResponse } } }); ``` -------------------------------- ### Arri Procedure Definition for POST Request Source: https://github.com/modiimedia/arri/blob/master/docs/implementing-an-arri-server.md Example of an Arri procedure definition in JSON, demonstrating how parameters are passed via the request body for a POST request. It defines the transport, method, path, parameters, and response types. ```json { "users.getUser": { "transport": "http", "method": "post", "path": "/users/get-user", "params": "GetUserParams", "response": "User" } } ``` -------------------------------- ### Call Standard HTTP Procedures in Arri Kotlin Client Source: https://github.com/modiimedia/arri/blob/master/languages/kotlin/kotlin-codegen/README.md Examples of calling standard HTTP procedures using the generated Arri Kotlin client. It shows how to call procedures with no parameters and with specific parameters. ```kotlin runBlocking { // procedure with no parameters val getUsersResponse = myClient.users.getUsers() // procedure with parameters val getUserResponse = myClient.users.getUser(GetUserParams(userId = "12345")) } ``` -------------------------------- ### Using arri.Pair for Key-Value Pairs in Go Source: https://github.com/modiimedia/arri/blob/master/languages/go/go-server/README.md The `arri.Pair` helper type represents a simple key-value pair in Go. This snippet shows examples of initializing `arri.Pair` with different data types, demonstrating its flexibility for various use cases. ```go arri.Pair("foo", "bar") arri.Pair(0, true) arri.Pair("baz", []string{}) ``` -------------------------------- ### Running Arri CLI Development and Build Commands Source: https://github.com/modiimedia/arri/blob/master/tooling/cli/README.md These commands are used to start the Arri server in development mode (`arri dev`), which watches for changes and rebuilds, or to build the server for production (`arri build`). An option to skip codegen during build is also shown. ```bash arri dev arri build ``` ```bash arri build --skip-codegen ``` -------------------------------- ### Add Non-RPC Routes using ArriApp Instance Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-server/README.md Shows how to define a generic HTTP route (e.g., GET /hello-world) directly on the `ArriApp` instance for non-RPC endpoints. ```ts // using the app instance const app = new ArriApp(); app.route({ method: "get", path: "/hello-world", handler(event) { return "hello world"; } }); ``` -------------------------------- ### Arri App Definition Procedures Object Examples Source: https://github.com/modiimedia/arri/blob/master/specifications/arri_app_definition.md Explains the structure of the 'procedures' object in the Arri app definition, which maps procedure names to their transport details, paths, methods, parameters, and responses. Demonstrates how to define single procedures and nest them into services. ```JSON { "getUser": { "transport": "http", "path": "/get-user", "method": "get", "params": "UserParams", "response": "User" } } ``` ```JSON { "users.getUser": { "transport": "http", "path": "/users/get-user", "method": "get", "params": "UserParams", "response": "User" }, "users.createUser": { "transport": "http", "path": "/users/create-user", "method": "post", "params": "User", "response": "User" } } ``` -------------------------------- ### Go Structs (Objects) in Arri Source: https://github.com/modiimedia/arri/blob/master/languages/go/go-server/README.md Arri supports Go structs as long as all fields are supported types. This example demonstrates defining simple and nested structs. ```Go type User struct { Id string Name string } type Post struct { Id string Author User // nested structs are okay too Content string } ``` -------------------------------- ### Define Arri RPC Procedure with Schema Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-server/README.md Example of a `.rpc.ts` file defining an Arri RPC procedure (`getUser`) with strongly typed parameters and response schemas using `@arrirpc/schema`. ```typescript // ./src/users/getUser.rpc.ts import { defineRpc } from '@arrirpc/server'; import { a } from '@arrirpc/schema'; export default defineRpc({ params: a.object({ userId: a.string() }), response: a.object({ id: a.string(), name: a.string(), createdAt: a.timestamp() }), handler({ params }) { // function body } }); ``` -------------------------------- ### Configure Arri for TypeScript Client Code Generation Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-codegen/README.md This snippet demonstrates how to add the TypeScript client generator to the `arri.config.ts` file. It shows the basic setup with `clientName` and `outputFile` options, which are crucial for generating the client. ```ts // arri.config.ts import { defineConfig, generators } from 'arri'; export default defineConfig({ generators: [ generators.typescriptClient({ clientName: 'MyClient', outputFile: './client/src/myClient.g.ts', }), ], }); ``` -------------------------------- ### Define Arri Models and RPCs using TypeScript Schema Builder Source: https://github.com/modiimedia/arri/blob/master/docs/implementing-an-arri-server.md This TypeScript example demonstrates how to define data models (`a.object`) and RPC (Remote Procedure Call) endpoints (`defineRpc`) using Arri's schema builder. This approach makes type and RPC definitions available at runtime, serving as the source of truth for automatic `AppDefinition` generation. ```typescript // Arri Models const UserParams = a.object("UserParams", { userId: a.string(), }); const User = a.object("User", { id: a.string(), name: a.string(), }); // RPC export const getUser = defineRpc({ params: UserParams, response: User, handler({ params }) { // some logic to get the user and return it }, }); ``` -------------------------------- ### Implement a Custom Event Type with User Data Source: https://github.com/modiimedia/arri/blob/master/languages/go/go-server/README.md This example demonstrates creating a custom `MyCustomEvent` type that embeds a `User` struct. It also shows how to implement the `Request()` and `Writer()` methods required by the `arri.Event` interface. ```go type User struct { Uid string Name string Email string } type MyCustomEvent struct { r *http.Request w httpResponseWriter User arri.Option[User] } func (e MyCustomEvent) Request() *http.Request { return e.r } func (e MyCustomEvent) Writer() http.ResponseWriter { return e.w } ``` -------------------------------- ### Configuring Arri Codegen for Client Generation Source: https://github.com/modiimedia/arri/blob/master/tooling/cli/README.md This `arri.config.ts` example shows how to set up client generators for Dart and TypeScript. It defines the client name and output path for each generated client, enabling type-safe client generation from an Arri App Definition. ```typescript // arri.config.ts import { defineConfig, generators } from 'arri'; export default defineConfig({ generators: [ generators.dartClient({ clientName: 'Client', outputPath: '' }), generators.typescriptClient({ clientName: 'Client', outputPath: '' }) // etc... ] }); ``` -------------------------------- ### Configure Arri CLI for Code Generation Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-schema/README.md Example of creating an `arri.config.ts` file to define and configure code generators for the Arri CLI. This configuration specifies which client languages (e.g., Rust, Dart) should have code generated from the defined Arri schemas. ```typescript import { defineConfig, generators } from 'arri'; export default defineConfig({ generators: [ // add your generators here generators.rustClient({ // options }), generators.dartClient({ // options }), ], }); ``` -------------------------------- ### Arri Command Line Interface (CLI) Commands Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-server/README.md The Arri CLI provides essential commands for managing Arri projects. These commands facilitate common development workflows, including starting a development server, creating production builds, initializing new projects, and running code generation based on the definition file. ```bash # start the dev server arri dev [flags] # create a production build arri build [flags] # create a new project arri init [dir] # run codegen arri codegen [path-to-definition-file] ``` -------------------------------- ### Generate Client Code with Arri CLI Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-schema/README.md This snippet shows how to use the Arri CLI's 'codegen' command to generate client-side code from the defined schemas. It provides examples for both 'npm' and 'pnpm' package managers, allowing developers to easily update generated code after schema changes. ```bash npx arri codegen ./definitions.ts ``` ```bash pnpm arri codegen ./definitions.ts ``` -------------------------------- ### JSON Object Demonstrating All Supported Data Types Source: https://github.com/modiimedia/arri/blob/master/tests/test-files/README.md A comprehensive JSON example showcasing various primitive and complex data types, including strings, booleans, timestamps, floats, integers (signed/unsigned, various sizes), enums, nested objects, arrays, records, discriminators, and 'any' type. ```json { "string": "", "boolean": false, "timestamp": "2001-01-01T16:00:00.000Z", "float32": 1.5, "float64": 1.5, "int8": 1, "uint8": 1, "int16": 10, "uint16": 10, "int32": 100, "uint32": 100, "int64": "1000", "uint64": "1000", "enum": "BAZ", "object": { "id": "1", "content": "hello world" }, "array": [true, false, false], "record": { "A": true, "B": false }, "discriminator": { "typeName": "C", "id": "", "name": "", "date": "2001-01-01T16:00:00.000Z" }, "any": "hello world" } ``` -------------------------------- ### Scaffold a New Arri Generator Project Source: https://github.com/modiimedia/arri/blob/master/docs/creating-a-custom-generator.md Use the `arri init` command to quickly set up a new generator project. The `--type plugin` flag ensures it's configured as a generator plugin, creating the necessary directory and initial files. ```bash arri init ./my-generator --type plugin ``` -------------------------------- ### Arri RPC Supported HTTP Methods and GET Parameter Handling Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-server/README.md Arri supports a range of standard HTTP methods for RPC procedures, including POST, GET, DELETE, PATCH, and PUT. When using the GET method, RPC parameters are automatically mapped as query parameters and coerced into their defined types using `arri-validate`'s `a.coerce` method. Note that GET methods only support basic scalar types; arrays and nested objects are not supported as query parameters. ```APIDOC Supported HTTP Methods: - post - get - delete - patch - put GET Method Parameter Handling: - RPC params mapped as query parameters. - Coerced into type using `a.coerce` from `arri-validate`. - Supports all basic scalar types. - Arrays and nested objects are NOT supported. ``` -------------------------------- ### Defining Nullable Types in Go with Pointers and arri.Nullable Source: https://github.com/modiimedia/arri/blob/master/languages/go/go-server/README.md Arri treats Go pointers as nullable during serialization, except for maps and arrays. This section illustrates how to define nullable fields using both pointers and the `arri.Nullable` type, showing the Go struct, its ATD output, and example JSON representations for set and null values. ```go type User struct { Id string Name *string // this is treated as nullable during encoding/decoding Email arri.Nullable[string] // this is also treated as nullable during encoding/decoding } ``` ```json { "properties": { "id": { "type": "string" }, "name": { "type": "string", "nullable": true }, "email": { "type": "string", "nullable": true } }, "metadata": { "id": "User" } } ``` ```json // with set nullable values / set pointers { "id": "1", "name": "john doe", "email": "johndoe@gmail.com" } ``` ```json // with unset nullable values / unset pointers { "id": "1", "name": null, "email": null } ``` -------------------------------- ### Get Validation Errors with a.errors() Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-schema/README.md Use `a.errors()` to get all of the validation errors of a given input against an arri schema, providing detailed information about each error. ```typescript const User = a.object({ id: a.string(), date: a.timestamp(), }); a.errors(User, { id: 1, date: 'hello world' }); /** * [ * { * instancePath: "/id", * schemaPath: "/properties/id/type", * message: "Expected string", * }, * { * instancePath: "/date", * schemaPath: "/properties/id/type", * message: "Expected instanceof Date", * } * ] * */ ``` -------------------------------- ### Arri RPC Application Entry Point Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-server/README.md Basic `app.ts` file showing the initialization of an `ArriApp` instance, serving as the main entry point for the Arri RPC server. ```typescript // ./src/app.ts import { ArriApp } from 'arri'; const app = new ArriApp(); export default app; ``` -------------------------------- ### Initialize Arri Application with Custom Event Factory Source: https://github.com/modiimedia/arri/blob/master/languages/go/go-server/README.md This code illustrates how to initialize an `arri` application using `arri.NewApp` with your custom event type. It includes a factory function that creates `MyCustomEvent` instances for each request, allowing for dynamic data population, such as fetching user details from an authorization token. ```go app := arri.NewApp( http.DefaultServeMux arri.AppOptions[MyCustomEvent]{}, // this function is used to create your custom event type whenever a new request is made func(w http.ResponseWriter, r *http.Request) (*MyCustomEvent, arri.RpcError) { authToken := r.Header.Get("Authorization") user := arri.None[User]{} if len(authToken) > 0 { // pseudo-code user = getUserFromAuthToken(authToken) } return &MyCustomEvent{ r: r, w: w, User: user, }, nil }, ) ``` -------------------------------- ### Registering Arri Server Plugins in arri.config.ts Source: https://github.com/modiimedia/arri/blob/master/tooling/cli/README.md This configuration snippet demonstrates how to register different server plugins (TypeScript and Go) within the `arri.config.ts` file. It shows how to define the source directory, entry file, and port for the TypeScript server, and how to include client generators. ```typescript // arri.config.ts import { defineConfig, servers } from 'arri'; // registering the typescript server plugin export default defineConfig({ server: servers.tsServer({ srcDir: 'src', entry: 'app.ts', port: 3000, }), generators: [ // client generators go here ] }); ``` ```typescript // registering the go server plugin export default defineConfig({ server: servers.goServer({}), generators: [ // client generators go here ] }); ``` -------------------------------- ### Initialize Arri Rust Client with Configuration Source: https://github.com/modiimedia/arri/blob/master/languages/rust/rust-codegen/README.md This Rust snippet shows how to initialize the generated Arri client (`MyClient`) by providing an `ArriClientConfig` struct, which includes an HTTP client, base URL, and headers. It then demonstrates calling a procedure. ```rust let config = ArriClientConfig { http_client: reqwest::Client::new(), base_url: "https://example.com".to_string(), headers: Hashmap::new(), } let client = MyClient::create(config); // start calling procedures client.my_procedure().await; ``` -------------------------------- ### Arri Kotlin Client/Service Initialization Options Source: https://github.com/modiimedia/arri/blob/master/languages/kotlin/kotlin-codegen/README.md Describes the common options available when initializing either the full Arri client or a specific service. These options include the HTTP client, base URL, headers, and an optional error hook. ```APIDOC ClientServiceOptions: httpClient: HttpClient An instance of ktor HttpClient baseUrl: String The base URL of the API server headers: (() -> MutableMap?)? A function that returns a map of http headers onError (Optional): ((err: Exception) -> Unit) A hook that fires whenever any exception is thrown by the client ``` -------------------------------- ### Initialize Arri Swift Root Client Source: https://github.com/modiimedia/arri/blob/master/languages/swift/swift-codegen/README.md This Swift code demonstrates how to initialize the root Arri client, `MyClient`, with a base URL, a request delegate, custom headers, and an optional error handler. It then shows a basic procedure call. ```swift let client = MyClient( baseURL: "https://example.com", delegate: DefaultRequestDelegate(), headers: { var headers: Dictionary = Dictionary() return headers }, // optional onError: { err in // do something } ) await client.myProcedure() ``` -------------------------------- ### JSON Object with All Nullable Fields Set to Null Source: https://github.com/modiimedia/arri/blob/master/tests/test-files/README.md An example of a JSON object where all fields that are defined as nullable are explicitly set to `null`, demonstrating how null values are represented. ```json { "string": null, "boolean": null, "timestamp": null, "float32": null, "float64": null, "int8": null, "uint8": null, "int16": null, "uint16": null, "int32": null, "uint32": null, "int64": null, "uint64": null, "enum": null, "object": null, "array": null, "record": null, "discriminator": null, "any": null } ``` -------------------------------- ### JSON Object with All Optional Fields Undefined Source: https://github.com/modiimedia/arri/blob/master/tests/test-files/README.md An example of a JSON object where all optional fields are omitted, resulting in an empty object. This demonstrates how optional fields are represented when not present. ```json {} ``` -------------------------------- ### Nested JSON Object Without Special Characters Source: https://github.com/modiimedia/arri/blob/master/tests/test-files/README.md Provides an example of a simple nested JSON object containing an ID and a content string without any special characters. ```json { "id": "1", "content": "hello world" } ``` -------------------------------- ### Run unit tests for ts-codegen-reference Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-codegen-reference/README.md Command to execute unit tests for the ts-codegen-reference library via Vitest using Nx. ```shell nx test ts-codegen-reference ``` -------------------------------- ### Customize Arri RPC File-Based Router Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-server/README.md Configuration example showing how to customize the directory and glob patterns for Arri RPC's file-based procedure router within `arri.config.ts`. ```typescript export default defineConfig({ servers: servers.tsServer({ procedureDir: 'procedures', // change which directory to look for procedures (This is relative to the srcDir) procedureGlobPatterns: ['**/*.rpc.ts'] // change the file name glob pattern for finding rpcs }), // rest of config }); ``` -------------------------------- ### Achieve Type Safety for Arri RPC Context Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-server/README.md Provides an example of how to augment the `ArriEventContext` interface in a `.d.ts` file to ensure type safety for custom properties added to the RPC context. ```ts import '@arrirpc/server'; declare module '@arrirpc/server' { interface ArriEventContext { user?: { id: number; name: string; email: string; }; } } ``` -------------------------------- ### Make Types Nullable with Arri's a.nullable Source: https://github.com/modiimedia/arri/blob/master/languages/ts/ts-schema/README.md Demonstrates how to use `a.nullable()` to allow a particular type to accept `null` as a valid value. The example shows the TypeScript type inference and the ATD representation. ```ts const name = a.nullable(a.string()); /** * Resulting type * string | null */ ``` ```json { "type": "string", "nullable": true } ``` -------------------------------- ### Define Arri Models and RPCs using Rust Procedural Macros Source: https://github.com/modiimedia/arri/blob/master/docs/implementing-an-arri-server.md For Rust implementations, Arri leverages procedural macros to define data models (`#[derive(ArriModel)]`) and RPC endpoints (`#[rpc]`). This allows for a code-first approach where the Rust code directly generates the necessary `AppDefinition`. ```rust #[derive(ArriModel)] struct UserParams { user_id: String, } #[derive(ArriModel)] struct User { id: String, name: String, } #[rpc("/users/get-user")] async fn get_user(params: UserParams) -> Result { // implementation here } ```