{"id":23380497,"url":"https://github.com/sov3rain/pocketbase-unity","last_synced_at":"2025-04-10T22:42:45.446Z","repository":{"id":268952525,"uuid":"887143532","full_name":"Sov3rain/pocketbase-unity","owner":"Sov3rain","description":"PocketBase Unity SDK","archived":false,"fork":false,"pushed_at":"2025-03-16T16:23:44.000Z","size":1544,"stargazers_count":6,"open_issues_count":0,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-24T19:39:37.231Z","etag":null,"topics":["pocketbase","sdk","unity","unity-package","unity3d"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Sov3rain.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-11-12T08:41:15.000Z","updated_at":"2025-03-20T13:19:40.000Z","dependencies_parsed_at":null,"dependency_job_id":"fb0d7ec9-4bf4-4f84-b5bb-b7d2a71e1f0f","html_url":"https://github.com/Sov3rain/pocketbase-unity","commit_stats":null,"previous_names":["sov3rain/pocketbase-unity"],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sov3rain%2Fpocketbase-unity","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sov3rain%2Fpocketbase-unity/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sov3rain%2Fpocketbase-unity/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sov3rain%2Fpocketbase-unity/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Sov3rain","download_url":"https://codeload.github.com/Sov3rain/pocketbase-unity/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248312208,"owners_count":21082638,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["pocketbase","sdk","unity","unity-package","unity3d"],"created_at":"2024-12-21T20:16:28.202Z","updated_at":"2025-04-10T22:42:45.438Z","avatar_url":"https://github.com/Sov3rain.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PocketBase Unity SDK\n\nUnofficial Multi-platform Unity C# SDK for interacting with the [PocketBase Web API](https://pocketbase.io/docs).\n\n- [PocketBase Unity SDK](#pocketbase-unity-sdk)\n  - [Supported Unity versions and platforms](#supported-unity-versions-and-platforms)\n  - [Supported PocketBase versions](#supported-pocketbase-versions)\n  - [Installation](#installation)\n  - [Usage](#usage)\n  - [Caveats](#caveats)\n    - [File upload](#file-upload)\n    - [RecordModel](#recordmodel)\n    - [Error handling](#error-handling)\n    - [AuthStore](#authstore)\n    - [Binding filter parameters](#binding-filter-parameters)\n    - [Extension Methods](#extension-methods)\n  - [Services](#services)\n  - [Development](#development)\n\n## Supported Unity versions and platforms\n\nThis package runs on Unity **2022.3 or later**. It has been tested on the following platforms:\n\n- Windows\n- MacOS\n- Linux\n- Android\n- iOS\n- WebGL\n\n## Supported PocketBase versions\n\nSome versions of PocketBase may not be compatible with some versions of this SDK. Please check the following table:\n\n| Unity SDK Version | PocketBase Version |\n| ----------------- | ------------------ |\n| 0.22.x            | 0.22.x             |\n| 0.23.x            | 0.23+              |\n\n## Installation\n\nOpen the *Package Manager* window, and click the *+* icon, then click on *Add package from git url*. Copy and paste the\nfollowing url and click *Add*:\n\n```bash\nhttps://github.com/Sov3rain/pocketbase-unity.git?path=/Assets/pocketbase-unity#0.23.2\n```\n\nThis will tag the package with a specific version.\n\nYou can also install the SDK by downloading the `.unitypackage` from the [releases page](https://github.com/Sov3rain/pocketbase-unity/releases) and importing it into your project.\n\n## Usage\n\n```csharp\nusing PocketBaseSdk;\nusing UnityEngine;\n\npublic class PocketBaseExample : MonoBehaviour\n{\n    private PocketBase pb;\n\n    private async void Start()\n    {\n        _pocketBase = new PocketBase(\"http://127.0.0.1:8090\");\n\n        // Authenticate as regular user\n        var userData = await pb.Collection(\"users\").AuthWithPassword(\"user@example.com\", \"password\");\n\n        // List and filter \"example\" collection records\n        var result = await pb.Collection(\"example\").GetList\u003cRecordModel\u003e(\n            page: 1,\n            perPage: 20,\n            filter: \"status = true \u0026\u0026 created \u003e= \\\"2022-08-01\\\"\",\n            sort: \"-created\",\n            expand: \"someRelField\"\n        );\n\n        // Subscribe to realtime \"example\" collection changes\n        pb.Collection(\"example\").Subscribe\u003cRecordModel\u003e(\"*\", e =\u003e\n        {\n            Debug.Log(e.Action); // \"create\", \"update\", \"delete\"\n            Debug.Log(e.Record); // The changed record\n        }, filter: \"someField \u003e 10\");\n    }\n}\n```\n\n## Caveats\n\n### File upload\n\nPocketBase Unity SDK handles file upload seamlessly by using [\n`IMultipartFormSection`](https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Networking.IMultipartFormSection.html)\nlist.\n\nHere is an example of uploading a single text file together with some other regular fields:\n\n```csharp\nusing PocketBaseSdk;\nusing UnityEngine;\n\npublic class PocketBaseExample : MonoBehaviour\n{\n    private PocketBase pb;\n\n    private async void Start()\n    {\n        pb = new PocketBase(\"http://127.0.0.1:8090\");\n\n        var record = await pb.Collection(\"example\").Create\u003cRecordModel\u003e(\n            body: new()\n            {\n                title = \"Hello, World!\"\n            },\n            files: new()\n            {\n                new MultipartFormFileSection(\n                    name: \"document\", // The name of the file field\n                    data: Encoding.UTF8.GetBytes(\"Hello, World!\"), // The file data\n                    fileName: \"example_document.txt\",\n                    contentType: \"text/plain\")\n            }\n        );\n\n        Debug.Log(record.Id);\n    }\n}\n```\n\n### RecordModel\n\nThe SDK comes with several helpers to make it easier working with the `RecordService` and `RecordModel` DTO. Below is an example on how to access and cast record data values:\n\n```csharp\nvar record = await pb.Collection(\"example\").GetOne(\"RECORD_ID\");\n\nvar options = record.Get\u003cList\u003cstring\u003e\u003e(\"options\");\nvar email   = record.Get\u003cstring\u003e(\"email\");\nvar status  = record.Get\u003cint\u003e(\"status\");\nvar price   = record.Get\u003cfloat\u003e(\"price\");\nvar nested1 = record.Get\u003cRecordModel\u003e(\"expand.user\", null);\nvar nested2 = record.Get\u003cstring\u003e(\"expand.user.title\", \"N/A\");\n```\n\nYou can also use the `RecordModel[string]` indexer:\n\n```csharp\nvar options = record[\"options\"]?.ToObject\u003cList\u003cstring\u003e\u003e();\nvar email   = record[\"email\"]?.ToString();\nvar status  = record[\"status\"]?.ToObject\u003cint\u003e();\nvar price   = record[\"price\"]?.ToObject\u003cfloat\u003e();\nvar nested1 = record[\"expand\"]?[\"user\"]?.ToObject\u003cRecordModel\u003e() ?? null;\nvar nested2 = record[\"expand\"]?[\"user\"]?[\"title\"]?.ToString() ?? \"N/A\";\n```\n\nAlternatively, you can also create your own typed DTO data classes and use a static factory method to populate your object, eg:\n\n```csharp\nusing PocketBaseSdk;\nusing UnityEngine;\n\npublic class Post : RecordModel\n{\n    public string Title { get; set; }\n    public string Content { get; set; }\n\n    public static Post FromRecord(RecordModel record) =\u003e \n        JsonConvert.DeserializeObject\u003cPost\u003e(record.ToString());\n}\n```\n\nAnd here is an example of how to use it:\n\n```csharp\n// Fetch your raw record\nvar record = await pb.Collection(\"posts\").GetOne(\"POST_ID\");\n\nvar post = Post.FromRecord(record);\n```\n\n### Error handling\n\nAll services return a standard Task object that can be awaited, so the error handling is pretty straightforward.\n\n```csharp\n// If you are using the async/await syntax:\ntry\n{\n    var userData = await pb.Collection(\"users\").AuthWithPassword(\"user@example.com\", \"password\");\n}\ncatch (ClientException e)\n{\n    // Handle error\n}\n\n// Or if you are using the ContinueWithOnMainThread syntax:\npb.Collection(\"users\").AuthWithPassword(\"user@example.com\", \"password\").ContinueWithOnMainThread(task =\u003e \n{\n    if (task.IsFaulted)\n    {\n        // Handle error\n    }\n    else if (task.IsCompleted)\n    {\n        var user = task.Result;\n    }\n});\n```\n\nAll responses errors are wrapped in a `ClientException` object, which contains the following properties:\n\n```csharp\npublic class ClientException : Exception\n{\n    public string Url { get; }\n    public int StatusCode { get; }\n    public Dictionary\u003cstring, object\u003e Response { get; }\n    public object OriginalError { get; }\n}\n```\n\n### AuthStore\n\nThe SDK keeps track of the authenticated token and auth record for you via the `PocketBase.AuthStore` service. The\ndefault AuthStore class has the following public properties:\n\n```csharp\npublic class AuthStore\n{\n    public string Token { get; }\n    public RecordModel Model { get; }\n    public bool IsValid();\n    public void Save(string newToken, RecordModel newModel);\n    public void Clear();\n}\n```\n\nTo *\"logout\"* an authenticated record, you can just call `PocketBase.AuthStore.Clear()`.\n\nTo *\"listen\"* for changes to the AuthStore, you can subscribe to the `PocketBase.AuthStore.OnChange` event:\n\n```csharp\npocketBase.AuthStore.OnChange.Subscribe(e =\u003e\n{\n    Debug.Log(e.Token);\n    Debug.Log(e.Model);\n});\n```\n\n**The default `AuthStore` is NOT persistent!**\n\nIf you want to persist the `AuthStore`, you can inherit from the default store and pass a new custom instance as\nconstructor argument to the client.\nTo make is slightly more convenient, the SDK has a built-in `AsyncAuthStore` that you can combine with any async\npersistent layer. Here is an example using Unity's `PlayerPrefs`:\n\n```csharp\nAsyncAuthStore store =\u003e new(\n    save: data =\u003e\n    {\n        UnityEngine.PlayerPrefs.SetString(\"pb_auth\", data);\n        return Task.CompletedTask; // Mandatory since SetString() is synchronous\n    },\n    initial: UnityEngine.PlayerPrefs.GetString(\"pb_auth\", string.Empty)\n);\n\nvar pb = new PocketBase(\n    \"http://127.0.0.1:8090\",\n    authStore: store\n);\n```\n\nYou can also use the `AsyncAuthStore.PlayerPrefs` static property, which will automatically save the AuthStore to the\nPlayerPrefs:\n\n```csharp\nvar pb = new PocketBase(\n    \"http://127.0.0.1:8090\",\n    authStore: AsyncAuthStore.PlayerPrefs\n);\n```\n\n### Binding filter parameters\n\nThe SDK comes with a helper `PocketBase.Filter(expr, params)` method to generate a filter string with placeholder\nparameters (`{paramName}`) populated from a `Dictionary\u003cstring, object\u003e`.\n\n```csharp\n// the same as: \"title ~ 'exa\\\\'mple' \u0026\u0026 created = '2023-10-18 18:20:00.123Z'\"\nvar filter = PocketBase.Filter(\n    \"title ~ {:title} \u0026\u0026 created \u003e= {:created}\", \n    new Dictionary\u003cstring, object\u003e\n    {\n        [\"title\"] = \"exa'mple\",\n        [\"created\"] = DateTime.UtcNow\n    }\n);\n\nvar record = await pb.Collection(\"example\").GetList\u003cRecordModel\u003e(filter: filter);\n```\n\n### Extension Methods\n\nThe SDK provides some helper methods to help with common tasks. \n\nOne of them is the `ContinueWithOnMainThread` method, which allows you to run a continuation task on the main thread. This is useful when you need to update the UI from a background thread, as Unity does not allow you to do this on any other thread:\n\n```csharp\nprivate Text _title;\n\n// This will run on the main thread\npb.Collection(\"users\").AuthWithPassword(\"user@example.com\", \"password\").ContinueWithOnMainThread(task =\u003e \n{\n    if (task.IsFaulted)\n    {\n        // Handle error\n    }\n    else if (task.IsCompleted)\n    {\n        var user = task.Result;\n        _title.text = user.Email; // Will throw an exception if called on a background thread\n    }\n});\n```\n\n## Services\n\nSee the [API documentation](https://pocketbase.io/docs/) for more information on the available services.\nYou can also check out the [Dart SDK](https://github.com/pocketbase/dart-sdk/tree/v0.18.1) documentation for more\ninformation on the available methods, as this SDK is a port of the Dart SDK.\n\n## Development\n\nClone the repository and open the project in Unity 2022.3. You can safely use any patch version of Unity 2022.3.\n\nThe SDK code is located in the `Assets/pocketbase-unity/` folder. This project uses the format of\nthe [Unity Package Manager](https://docs.unity3d.com/Manual/upm-ui-giturl.html) to distribute the SDK.\n\nThe only dependency is the [Newtonsoft.Json](https://www.nuget.org/packages/Newtonsoft.Json/) package, which is included\nin the Unity Package Manager. The rest of the code is written in fully managed C# for maximum platform compatibility.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsov3rain%2Fpocketbase-unity","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsov3rain%2Fpocketbase-unity","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsov3rain%2Fpocketbase-unity/lists"}