### Pinia ORM Model with Setup Store Options Source: https://pinia-orm.codedredd.de/changelog Shows an example of a Pinia ORM model utilizing the setup store syntax with `piniaOptions` and `piniaExtend` for defining new data properties and extending store behavior, such as persistence. ```javascript class User extends Model { static entity = 'users' static piniaOptions = { newData: ref('1'), } static piniaExtend = { persist: true, } @Attr(0) declare id: number @Str('') declare name: string @Str('') declare username: string } console.log(userRepo.piniaStore().newData) // 1 ``` -------------------------------- ### Configure Pinia ORM with Setup Stores Source: https://pinia-orm.codedredd.de/guide/getting-started/configuration Use this option to enable setup store logic within Pinia ORM. This is the primary way to integrate setup store features. ```javascript createPiniaORM({ pinia: { storeType: 'setupStore' } }) ``` -------------------------------- ### Generate UUID Example Source: https://pinia-orm.codedredd.de/guide/model/getting-started This example shows how to generate a UUID and access it after creating a user record. ```javascript const user = useRepo(User).make() user.id // <- '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d' ``` -------------------------------- ### Install Nanoid Source: https://pinia-orm.codedredd.de/guide/model/getting-started Install the nanoid package using Yarn or NPM to use it with Pinia ORM. ```bash yarn add nanoid ``` ```bash npm install nanoid --save ``` -------------------------------- ### Normalized State Structure Example Source: https://pinia-orm.codedredd.de/guide/getting-started/what-is-pinia-orm This example demonstrates a normalized state structure for blog posts, comments, and users. Each data type is stored in its own object with IDs as keys, facilitating easier data management and updates. ```json { posts: { 1: { id: 1, user_id: 1, body: '.....' }, 2: { id: 2, user_id: 2, body: '.....' } }, comments: { 1: { id: 1, user_id: 2, post_id: 1, comment: '.....' }, 2: { id: 2, user_id: 2, post_id: 1, comment: '.....' }, 3: { id: 3, user_id: 3, post_id: 2, comment: '.....' }, 4: { id: 4, user_id: 1, post_id: 2, comment: '.....' }, 5: { id: 5, user_id: 3, post_id: 2, comment: '.....' } }, users: { 1: { id: 1, name: 'User 1' }, 2: { id: 2, name: 'User 2' }, 3: { id: 3, name: 'User 3' } } } ``` -------------------------------- ### Install Pinia ORM Axios Plugin (NPM) Source: https://pinia-orm.codedredd.de/plugins/axios/guide/setup Use this command to add the plugin to your project using NPM. ```bash npm install @pinia-orm/axios --save ``` -------------------------------- ### Install Pinia ORM Axios Plugin (PNPM) Source: https://pinia-orm.codedredd.de/plugins/axios/guide/setup Use this command to add the plugin to your project using PNPM. ```bash pnpm add @pinia-orm/axios ``` -------------------------------- ### Install UUID Source: https://pinia-orm.codedredd.de/guide/model/getting-started Install the uuid package using Yarn or NPM to use it with Pinia ORM. ```bash yarn add uuid ``` ```bash npm install uuid --save ``` -------------------------------- ### Install Pinia ORM Axios Plugin (Yarn) Source: https://pinia-orm.codedredd.de/plugins/axios/guide/setup Use this command to add the plugin to your project using Yarn. ```bash yarn add @pinia-orm/axios ``` -------------------------------- ### Install Pinia ORM with NPM Source: https://pinia-orm.codedredd.de/guide/getting-started/quick-start Use NPM to add Pinia ORM to your project dependencies. ```bash npm install pinia-orm --save ``` -------------------------------- ### Perform GET Request Source: https://pinia-orm.codedredd.de/plugins/axios/api/request Use the `get` method to perform an HTTP GET request. It accepts a URL and optional Axios configuration object. ```javascript get(url: string, config: Config = {}): Promise ``` -------------------------------- ### Install Pinia ORM with NPM Source: https://pinia-orm.codedredd.de/guide/nuxt/setup Use this command to add Pinia ORM and its Nuxt integration package to your project using NPM. ```bash npm install @pinia-orm/nuxt --save ``` -------------------------------- ### Install Pinia ORM with Yarn Source: https://pinia-orm.codedredd.de/guide/getting-started/quick-start Use Yarn to add Pinia ORM to your project dependencies. ```bash yarn add pinia-orm ``` -------------------------------- ### Query Data with Chained Repository Methods Source: https://pinia-orm.codedredd.de/guide/repository/getting-started Demonstrates a common query pattern using chained methods like `where`, `orderBy`, and `get` on a repository. ```javascript useRepo(Post) .where('public', true) .orderBy('publishedAt', 'desc') .get() ``` -------------------------------- ### Install Pinia ORM with PNPM Source: https://pinia-orm.codedredd.de/guide/getting-started/quick-start Use PNPM to add Pinia ORM to your project dependencies. ```bash pnpm add pinia-orm ``` -------------------------------- ### Import and Use useRepo() Source: https://pinia-orm.codedredd.de/api/composables/use-repo Import the useRepo composable and use it to get repository instances for your models or custom repository classes. Ensure models and repositories are correctly imported. ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' import PostRepository from './repositories/Post' const userRepo = useRepo(User) // Repository const postRepo = useRepo(PostRepo) // PostRepository ``` -------------------------------- ### Initialize Request Object Source: https://pinia-orm.codedredd.de/plugins/axios/api/request Obtain the Request object by calling the `api()` method on a repository. This object is the starting point for all API interactions. ```javascript const request = useAxiosRepo(User).api() ``` -------------------------------- ### Install Pinia ORM with Yarn Source: https://pinia-orm.codedredd.de/guide/nuxt/setup Use this command to add Pinia ORM and its Nuxt integration package to your project using Yarn. ```bash yarn add pinia-orm @pinia-orm/nuxt ``` -------------------------------- ### Pinia ORM useCache() Usage Examples Source: https://pinia-orm.codedredd.de/api/query/use-cache Demonstrates how to use the useCache() method with different key generation strategies. It's recommended to use manual keys for better control and predictability. ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' // Generate a cache with a auto generated key. useRepo(User).useCache().get() // Generate a cache with a manual key (recommanded). useRepo(User).useCache('key').get() // Generate a cache with a manual key and dynamic params (recommanded). useRepo(User).useCache('key', { id: idProperty }).get() ``` -------------------------------- ### Retrieve Primary Keys with useKeys Source: https://pinia-orm.codedredd.de/api/composables/helpers/use-keys Import and use the useKeys helper to get all primary keys from a collection of models. Ensure you have imported 'useRepo' and your model. ```javascript import { useRepo } from 'pinia-orm' import { useKeys } from 'pinia-orm/helpers' import User from './models/User' const users = useRepo(User).all() // retrieve all primary keys useKeys(users) ``` -------------------------------- ### Using Pinia ORM Outside of Setup() Source: https://pinia-orm.codedredd.de/guide/getting-started/usage When using Pinia ORM outside of a Vue component's setup function, you must pass the Pinia instance to `useRepo`. This ensures the repository can access the Pinia store correctly. ```javascript import User from '@/models/User' import { createApp } from 'vue' import App from './App.vue' // ❌ fails because it's called before the pinia is created const userRepo = useRepo(User) // ✅ works because the pinia instance is passed to defineStore const userRepo = useRepo(User, this.$pinia) ``` -------------------------------- ### Standard Repository Usage with Pinia ORM Source: https://pinia-orm.codedredd.de/guide/getting-started/usage Use `useRepo` to get a repository instance for a model. This is the standard way to interact with your data within a store. ```javascript import User from './models/User' import { useRepo } from 'pinia-orm' const userRepo = useRepo(User) // Getting all users with their todos as relation const users = userRepo.with('todos').get() ``` -------------------------------- ### Configure Axios Get Request Source: https://pinia-orm.codedredd.de/plugins/axios/guide/usage Configure a GET request with Axios options like `baseURL` and plugin options like `dataKey` to specify where resources are nested in the response. ```javascript useAxiosRepo(User).api().get('/api/users', { baseURL: 'https://example.com/', dataKey: 'result' }) ``` -------------------------------- ### useRepo() Source: https://pinia-orm.codedredd.de/api/composables/use-repo The `useRepo` composable function is used to get an instance of a repository. It can be used with a model class to get a default repository or with a custom repository class to get an instance of that specific repository. ```APIDOC ## `useRepo()` ### Description The `useRepo` composable function is used to get an instance of a repository. It can be used with a model class to get a default repository or with a custom repository class to get an instance of that specific repository. ### Usage ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' import PostRepository from './repositories/Post' const userRepo = useRepo(User) // Returns Repository const postRepo = useRepo(PostRepo) // Returns PostRepository ``` ### Type Declaration ```typescript export function useRepo(model: Constructor, pinia?: Pinia): Repository export function useRepo(repository: Constructor, pinia?: Pinia): R ``` ``` -------------------------------- ### get() Method Source: https://pinia-orm.codedredd.de/api/query/get Retrieves records from the repository. It can fetch all records or apply filters before retrieval. ```APIDOC ## `get()` ### Description Executes the query and retrieves all matching records. ### Method `get(): Collection` ### Parameters This method does not accept any parameters. ### Usage Examples ```javascript // Get all users const users = userRepo.query().get() // Get users with a specific prename const usersPreName = userRepo.where('prename', 'John').get() ``` ### Response - Returns a `Collection` containing the retrieved model instances. ``` -------------------------------- ### Get Pinia Store Instance Source: https://pinia-orm.codedredd.de/guide/model/pinia-options Access the Pinia store instance for a model using `useRepo(Model).piniaStore()` to interact with its state. ```javascript const userRepo = useRepo(User) console.log(userRepo.piniaStore().state.value) ``` -------------------------------- ### Retrieve First User by Name Source: https://pinia-orm.codedredd.de/api/query/first Use the `first()` method after applying filters with `where()` to get the first matching user. Ensure the User model and repository are imported. ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' const userRepo = useRepo(User) console.log(userRepo.where('prename', 'John').first()) // User - with prename 'John' ``` -------------------------------- ### Access Pinia Store Instance Source: https://pinia-orm.codedredd.de/api/repository/pinia-store Import the useRepo function and the model, then call useRepo(Model).piniaStore() to get the store instance. This is useful for direct store manipulation. ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' // Return the complete pinia Store instance useRepo(User).piniaStore() ``` -------------------------------- ### all() Method Source: https://pinia-orm.codedredd.de/api/query/all The `all()` method retrieves all models from the repository. Unlike `get()`, it does not process any query chain and always returns all available models. ```APIDOC ## `all()` ### Description Retrieves all models from the repository without processing any query chain. ### Method Signature ```typescript function all(): Collection ``` ### Usage Examples ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' const userRepo = useRepo(User) // Retrieve all users const users = userRepo.query().all() // Returns Collection // Example showing that query chains are ignored by all() const usersPreName = userRepo.where('prename', 'John').all() // Returns Collection - still all users ``` ### Return Value - `Collection`: A collection containing all models of type `M`. ``` -------------------------------- ### Load Nested Relationships Source: https://pinia-orm.codedredd.de/guide/relationships/getting-started Load nested relationships by passing a callback to the `with()` method. This example loads authors for books and then contacts for each author. ```javascript const books = useRepo(Book).with('author', (query) => { query.with('contacts') }).get() ``` -------------------------------- ### Example Nested Data Structure Source: https://pinia-orm.codedredd.de/guide/getting-started/what-is-pinia-orm Illustrates a common nested and potentially duplicated data structure fetched from a backend, highlighting the issues with managing such data directly in a store. ```json [ { id: 1, body: '.....', author: { id: 1, name: 'User 1' }, comments: [ { id: 1, comment: '.....', author: { id: 2, name: 'User 2' } }, { id: 2, comment: '.....', author: { id: 2, name: 'User 2' } } ] }, { id: 2, author: { id: 2, name: 'User 2' }, body: '.....', comments: [ { id: 3, comment: '.....', author: { id: 3, name: 'User 3' } }, { id: 4, comment: '.....', author: { id: 1, name: 'User 1' } }, { id: 5, comment: '.....', author: { id: 3, name: 'User 3' } } ] } // And so on... ] ``` -------------------------------- ### Retrieve All or Filtered Users with get() Source: https://pinia-orm.codedredd.de/api/query/get Use this snippet to fetch all users or filter users based on a specific attribute. Ensure the User model and repository are imported and initialized. ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' const userRepo = useRepo(User) const users = userRepo.query().get() // User[] - all const usersPreName = userRepo.where('prename', 'John').get() // User[] - with prename 'John' ``` -------------------------------- ### String Cast Example Source: https://pinia-orm.codedredd.de/api/model/options/casts Use StringCast to ensure a field is treated as a string. This is useful for fields like 'firstName' that should always be a string. ```javascript import { Model } from 'pinia-orm' import { StringCast } from 'pinia-orm/casts' class User extends Model { static entity = 'users' static fields() { return { id: this.attr(null), firstName: this.string('') } } static casts() { return { firstName: StringCast } } } ``` -------------------------------- ### whereIn() Usage Source: https://pinia-orm.codedredd.de/api/query/where-in Demonstrates how to use the `whereIn()` method to filter records. It shows examples of filtering by an array of IDs and by a Set of IDs. ```APIDOC ## `whereIn()` ### Description Filters records where a specified field's value is present in a given array or Set. ### Method Signature `whereIn(field: string, values: any[]|Set): Query` ### Usage Examples #### Filter by Array ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' const userRepo = useRepo(User) console.log(userRepo.query().whereIn('commentIds', [1, 2, 5]).get()) ``` #### Filter by Set ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' const userRepo = useRepo(User) console.log(userRepo.query().whereIn('commentIds', new Set([1, 2, 5])).get()) ``` ### Parameters #### `field` (string) - Required The name of the field to filter on. #### `values` (any[] | Set) - Required An array or a Set of values to match against the specified field. ``` -------------------------------- ### Pinia ORM orderBy() Usage Examples Source: https://pinia-orm.codedredd.de/api/query/order-by Demonstrates how to use the orderBy() method to sort query results by a field name, chain multiple orderBy() calls for complex sorting, and sort by a computed property or custom logic. ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' const userRepo = useRepo(User) // Order users by name. useRepo(User).orderBy('name').get() // You may also chain orderBy. useRepo(User) .orderBy('name') .orderBy('age', 'desc') .get() // Sort user name by its third character. useRepo(User).orderBy(user => user.name[2]).get() ``` -------------------------------- ### Insert Data for Derived Entity Source: https://pinia-orm.codedredd.de/guide/model/single-table-inheritance Use the repository static methods to insert data for a derived entity. This example shows how to insert a record for the `Adult` entity. ```javascript useRepo(Adult).insert({id: 1, name: 'John Doe', job: 'Software Engineer' }) ``` -------------------------------- ### Retrieve a Repository for a Model Source: https://pinia-orm.codedredd.de/guide/repository/getting-started Use the `useRepo` method to get a repository instance for a specific model. This repository can then be used to perform CRUD operations. ```javascript const userRepo = useRepo(User) userRepo.save(...) ``` -------------------------------- ### Persist Response Data to Store Source: https://pinia-orm.codedredd.de/plugins/axios/guide/usage By default, response data is automatically saved to the store. This example shows a basic GET request where the response will be persisted. ```javascript useAxiosRepo(User).api().get('https://example.com/api/users') ``` -------------------------------- ### Constrain Relationship Query Source: https://pinia-orm.codedredd.de/guide/relationships/getting-started Load a relationship with specific query conditions. This example loads only published posts for users, or orders posts by creation date. ```javascript const users = useRepo(User).with('posts', (query) => { query.where('published', true) }).get() ``` ```javascript const users = useRepo(User).with('posts', (query) => { query.orderBy('createdAt', 'desc') }).get() ``` -------------------------------- ### Using useMin() to Get Minimum Values Source: https://pinia-orm.codedredd.de/api/composables/helpers/use-min Import necessary functions and models, fetch a collection of users, and then use useMin() to find the minimum value of the 'age' attribute or the 'role.title' attribute for one-to-one relations. ```javascript import { useRepo } from 'pinia-orm' import { useMin } from 'pinia-orm/helpers' import User from './models/User' const users = useRepo(User).all() // get the min of the 'age' attribute useMin(users, 'age') // get the min of the 'role.title' attribute. The dot notation works only for 1n1 Relations useMin(users, 'role.title') ``` -------------------------------- ### Add Custom Plugin to Pinia ORM Instance Source: https://pinia-orm.codedredd.de/plugins/introduction Integrate your custom plugin into the Pinia ORM instance during setup. Ensure Pinia and the ORM are correctly configured and activated. ```javascript import { createPinia, setActivePinia } from 'pinia' import { createORM } from 'pinia-orm' import { createApp } from 'vue' import { piniaOrmPlugin } from './plugins' const app = createApp({}) const pinia = createPinia() const piniaOrm = createORM({ plugins: [ piniaOrmPlugin() ], }) pinia.use(piniaOrm) app.use(pinia) setActivePinia(pinia) ``` -------------------------------- ### useCache() Method Source: https://pinia-orm.codedredd.de/api/query/use-cache Demonstrates how to use the useCache() method with different key and parameter configurations. ```APIDOC ## useCache() ### Description Enables caching for Pinia ORM queries. You can use an auto-generated key, a manual key, or a manual key with dynamic parameters for more control over caching. ### Method Signature ```typescript function useCache(key?: string, params?: Record): Query ``` ### Usage Examples **1. Generate a cache with an auto-generated key:** ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' useRepo(User).useCache().get() ``` **2. Generate a cache with a manual key (recommended):** ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' useRepo(User).useCache('user-list').get() ``` **3. Generate a cache with a manual key and dynamic parameters (recommended):** ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' const userId = 1 useRepo(User).useCache('user-details', { id: userId }).get() ``` ### Parameters - **key** (string, optional): A manual key to identify the cache. If not provided, a key will be auto-generated. - **params** (Record, optional): An object containing dynamic parameters to be included in the cache key. This is useful for creating unique cache entries based on query variations. ``` -------------------------------- ### Check for Composite Key in Model Instance Source: https://pinia-orm.codedredd.de/api/model/functions/has-composite-key Instantiate a model and use the $hasCompositeKey() method to check if it has a composite key. This example demonstrates its usage with a simple model that does not have a composite key. ```javascript class User extends Model { static entity = 'users' @Attr('') declare id: number @Str('') declare name: string } const user = new User({ id: 1, name: 'John Doe' }) user.$hasCompositeKey() // -> false ``` -------------------------------- ### Get Primary Key of a User Model Instance Source: https://pinia-orm.codedredd.de/api/model/functions/get-key Instantiate a User model and call $getKey() to retrieve its primary key. Ensure the model has an 'id' field defined as the primary key. ```javascript class User extends Model { static entity = 'users' @Attr('') declare id: number @Str('') declare name: string } const user = new User({ id: 1, name: 'John Doe' }) user.$getKey() // -> 1 ``` -------------------------------- ### TypeScript Declaration for get() Source: https://pinia-orm.codedredd.de/api/query/get This shows the TypeScript signature for the get() method, indicating it returns a Collection of model instances. ```typescript function get(): Collection ``` -------------------------------- ### Configure Pinia ORM Auto Imports in Nuxt Source: https://pinia-orm.codedredd.de/guide/nuxt/setup Customize auto imports for Pinia ORM in your Nuxt configuration. This example shows how to add 'useRepo' and an aliased version 'usePinaRepo'. ```typescript // nuxt.config.ts export default defineNuxtConfig({ // ... other options modules: ['@pinia/nuxt', '@pinia-orm/nuxt'], piniaOrm: { autoImports: [ // automatically imports `useRepo` 'useRepo', // import { useRepo } from 'pinia-orm' ['useRepo', 'usePinaRepo'], // import { useRepo as usePinaRepo } from 'pinia-orm' ], }, }) ``` -------------------------------- ### Get Model Attributes - Pinia ORM Source: https://pinia-orm.codedredd.de/api/model/functions/get-attributes Use $getAttributes() to get a plain object of the model's attributes. This excludes any defined relationships. ```javascript class User extends Model { static entity = 'users' @Attr('') declare id: number @Str('') declare name: string @HasMany(() => Post, 'userId') declare posts: Post[] } const user = new User({ id: 1, name: 'John Doe', posts: [{ id: 1, title: 'Merry Christmas' }] }) user.$getAttributes() // { // id: 1, // name: 'John Doe', // } ``` -------------------------------- ### Create a Custom Repository Source: https://pinia-orm.codedredd.de/guide/repository/getting-started Extend the base `Repository` class to create a custom repository. Define the `use` property to link it to a specific model. ```javascript import { Repository } from 'pinia-orm' import Post from '@/models/Post' class PostRepository extends Repository { use = Post } ``` -------------------------------- ### TypeScript Declarations for Hidden Fields Source: https://pinia-orm.codedredd.de/api/model/options/hidden Example of TypeScript type declarations for hidden fields. Note that this is a basic example and might require adjustments based on your specific model structure. ```typescript const visible: hidden[] = [] ``` -------------------------------- ### Using offset() to Skip Records Source: https://pinia-orm.codedredd.de/api/query/offset Import the useRepo function and your model, then use offset() to skip a specified number of records before fetching the results. This example skips the last 30 users. ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' const userRepo = useRepo(User) // Remove the last 30 users useRepo(User).offset(30).get() ``` -------------------------------- ### Listen to Repository Actions with Pinia Store Source: https://pinia-orm.codedredd.de/guide/model/lifecycle-hooks Use the repository's `piniaStore().$onAction` method to listen for specific repository actions like `delete`, `insert`, `update`, etc. This allows you to hook into action execution, success, or failure. ```javascript const userRepo = useRepo(User) userRepo.piniaStore().$onAction(({ name, // name of the action // store, // store instance, same as `someStore` args, // array of parameters passed to the action after, // hook after the action returns or resolves onError, // hook if the action throws or rejects }) => { // a shared variable for this specific action call const startTime = Date.now() // this will trigger before an action on `store` is executed console.log(`Start "${name}" with params [${args.join(', ')}].`) // this will trigger if the action succeeds and after it has fully run. // it waits for any returned promised after((result) => { console.log( `Finished "${name}" after ${ Date.now() - startTime }ms.\nResult: ${result}.`, ) }) // this will trigger if the action throws or returns a promise that rejects onError((error) => { console.warn( `Failed "${name}" after ${Date.now() - startTime}ms.\nError: ${error}.`, ) }) }) ``` -------------------------------- ### Define a Custom Fetch Action Source: https://pinia-orm.codedredd.de/plugins/axios/guide/custom-actions Define a 'fetch' action with a GET method and a specific URL within the model's configuration. This action can then be called directly on the repository's API instance. ```javascript class User extends Model { static entity = 'users' static fields () { return { id: this.attr(null), name: this.attr('') } } static config = { axiosApi: { actions: { fetch: { method: 'get', url: '/api/users' } } } } } ``` -------------------------------- ### Define Model Configurations with Pinia Options and Extend Source: https://pinia-orm.codedredd.de/guide/getting-started/configuration Define model-specific configurations using `piniaOptions` for direct options and `piniaExtend` for passing configurations to other Pinia plugins, such as persistence. ```javascript class User extends Model { static entity = 'users' static piniaOptions = { newData: ref('1'), } static piniaExtend = { persist: true, } @Attr(0) declare id: number @Str('') declare name: string @Str('') declare username: string } ``` -------------------------------- ### Retrieve Models with Constraints Source: https://pinia-orm.codedredd.de/guide/repository/retrieving-data Add constraints to your queries using the `where()` method before calling `get()` to retrieve specific records. ```javascript // Get all active users. const users = useRepo(User).where('active', true).get() ``` -------------------------------- ### Fetch All Users with Axios Source: https://pinia-orm.codedredd.de/plugins/axios/guide/usage Instantiate a new axios request for a repository to fetch all users and persist the response to the store. ```javascript await useAxiosRepo(User).api().get('https://example.com/api/users') ``` -------------------------------- ### Configure Global Axios Instance and Headers Source: https://pinia-orm.codedredd.de/plugins/axios/guide/configuration Configure the plugin globally with an axios instance, baseURL, and common headers for all requests. ```javascript import axios from 'axios' import { createORM } from 'pinia-orm' import { createPiniaOrmAxios } from '@pinia-orm/axios' const piniaOrm = createORM({ plugins: [ createPiniaOrmAxios({ axios, headers: { 'X-Requested-With': 'XMLHttpRequest' }, baseURL: 'https://example.com/api/' }), ] }) ``` -------------------------------- ### Instantiate Pinia ORM Models with make() Source: https://pinia-orm.codedredd.de/api/repository/make Use `make()` to create model instances without persisting them to the store. This is useful for SSR environments. It supports creating single models with default values, single models with specific attributes, or multiple models from an array. ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' const userRepo = useRepo(User) // Make a model with default values userRepo.make() // Make a model with values userRepo.make({ id: 1, name: 'Jane Doe', }) // Make many models with values userRepo.make([ { id: 1, name: 'Jane Doe', }, { id: 2, name: 'John Doe', }, ]) ``` -------------------------------- ### Number Cast Example Source: https://pinia-orm.codedredd.de/api/model/options/casts Use NumberCast to ensure a field is treated as a number. This is suitable for numerical data like 'age'. ```javascript import { Model } from 'pinia-orm' import { NumberCast } from 'pinia-orm/casts' class User extends Model { static entity = 'users' static fields() { return { id: this.attr(null), age: this.number(0) } } static casts() { return { age: NumberCast } } } ``` -------------------------------- ### Define a User Model Source: https://pinia-orm.codedredd.de/guide/model/getting-started Sets up a basic User model with 'id' and 'name' fields using generic attributes. The 'entity' property identifies the model, and 'fields' defines the schema. ```javascript import { Model } from 'pinia-orm' class User extends Model { static entity = 'users' static fields () { return { id: this.attr(null), name: this.attr('John Doe') } } } ``` -------------------------------- ### Create an Abstract Custom Repository Source: https://pinia-orm.codedredd.de/guide/repository/getting-started Create an abstract repository by extending `Repository` without the `use` property. This allows interaction with multiple models within a single repository. ```javascript import { Repository } from 'pinia-orm' import PostCategory from '@/models/PostCategory' import PostType from '@/models/PostType' class PostMetaRepository extends Repository { getCategoryAndType () { return { category: this.getCategory(), type: this.getType() } } getCategory () { return this.repo(PostCategory).all() } getType () { return this.repo(PostType).all() } } ``` -------------------------------- ### Equivalent API Request Source: https://pinia-orm.codedredd.de/plugins/axios/guide/custom-actions This demonstrates that calling the custom 'fetch' action is equivalent to making a direct API request with the specified method and URL. ```javascript useAxiosRepo(User).api().request({ method: 'get', url: '/api/users' }) ``` -------------------------------- ### Filtering records where a field is null Source: https://pinia-orm.codedredd.de/api/query/where-null This example demonstrates how to use the `whereNull` method to retrieve all users whose 'age' field is null. ```APIDOC ## `whereNull()` ### Description Adds a `WHERE` clause to the query to select all results where the specified `field` is null. ### Method Signature ```typescript function whereNull( field: string, ): Query ``` ### Parameters #### Path Parameters - **field** (string) - Required - The name of the field to check for null values. ### Usage Example ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' const userRepo = useRepo(User) console.log(userRepo.whereNull('age').get()) // Returns an array of User objects where 'age' is null. ``` ### Related Methods - `whereNotNull()`: Adds a `WHERE` clause to get all results where `field` is not null. - `where()`: Adds a basic `WHERE` clause to the query. ``` -------------------------------- ### Create New Model Instance with `new()` Source: https://pinia-orm.codedredd.de/api/repository/new Use this method to create a new model instance. By default, it will be persisted and fire hooks. Pass `false` to create a model that will not be persisted. ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' const userRepo = useRepo(User) // Make a model with default values which will be persisted userRepo.new() // Make a model with default values which will not be persisted userRepo.new(false) ``` -------------------------------- ### Boolean Cast Example Source: https://pinia-orm.codedredd.de/api/model/options/casts Use BooleanCast to ensure a field is treated as a boolean. This is appropriate for flags or status indicators like 'registered'. ```javascript import { Model } from 'pinia-orm' import { BooleanCast } from 'pinia-orm/casts' class User extends Model { static entity = 'users' static fields() { return { id: this.attr(null), registered: this.boolean(false) } } static casts() { return { registered: BooleanCast } } } ``` -------------------------------- ### Use Custom Repository Method Source: https://pinia-orm.codedredd.de/guide/repository/getting-started Call custom methods defined on your custom repository by passing the custom repository class to `useRepo`. ```javascript useRepo(PostRepository).getLatestPublished() ``` -------------------------------- ### Chaining Request Methods Source: https://pinia-orm.codedredd.de/plugins/axios/api/request You can directly chain API request methods like `get()` onto the Request object for concise API calls. ```javascript const response = useAxiosRepo(User).api().get() ``` -------------------------------- ### Retrieve First Model Matching Constraints Source: https://pinia-orm.codedredd.de/guide/repository/retrieving-data Use the `first()` method after applying constraints with `where()` to retrieve the first model instance that matches the query. ```javascript // Retrieve the first model matching the query constraints. const user = useRepo(User).where('active', true).first() ``` -------------------------------- ### Get Index ID of a User Model Source: https://pinia-orm.codedredd.de/api/model/functions/get-index-id Instantiate a User model and call the $getIndexId() method to retrieve its ID. The ID is returned as a string. ```javascript class User extends Model { static entity = 'users' @Attr('') declare id: number @Str('') declare name: string } const user = new User({ id: 1, name: 'John Doe' }) user.$getIndexId() // -> '1' ``` -------------------------------- ### Load All Top-Level Relationships Source: https://pinia-orm.codedredd.de/guide/relationships/getting-started Use `withAll` to fetch models and all their direct relationships. Constraints applied to `withAll` will affect all loaded relationships. ```javascript // Fetch models with all top-level relationships. useRepo(User).withAll().get() ``` ```javascript // As above, with a constraint. useRepo(User).withAll((query) => { // This constraint will apply to all of the relationship User has. For this // example, all relationship will be sorted by `createdAt` field. query.orderBy('createdAt') }).get() ``` -------------------------------- ### Configure Global Default Field Visibility Source: https://pinia-orm.codedredd.de/guide/model/getting-started Set default hidden and visible fields for all models in the ORM setup using the `createORM` configuration. ```javascript const app = createApp({}) const pinia = createPinia() pinia.use(createORM({ model: { visible: ['*'], hidden: [] } })) app.use(pinia) setActivePinia(pinia) ``` -------------------------------- ### Extend Pinia Store Options with persist: true Source: https://pinia-orm.codedredd.de/guide/model/pinia-options Use `piniaOptions` to pass configuration to the Pinia store, such as enabling persistence with `persist: true`. ```typescript import { Model } from 'pinia-orm' import { Attr, Str } from 'pinia-orm/decorators' import Post from '@/models/Post' class User extends Model { static entity = 'users' @Attr(null) declare id: number | null @Str('') declare name: string static piniaOptions = { persist: true } } ``` -------------------------------- ### Convert Model Instance to JSON Source: https://pinia-orm.codedredd.de/api/model/functions/to-json Use the $toJson() method on a model instance to get its data as a JSON object. This includes all attributes and related data. ```javascript class User extends Model { static entity = 'users' @Attr('') declare id: number @Str('') declare name: string @HasMany(() => Post, 'userId') declare posts: Post[] } const user = new User({ id: 1, name: 'John Doe', posts: [{ id: 1, title: 'Merry Christmas' }] }) user.$toJson() // { // id: 1, // name: 'John Doe', // posts: [{ id: 1, title: 'Merry Christmas' }], // } ``` -------------------------------- ### Registering Plugins with Pinia ORM Source: https://pinia-orm.codedredd.de/changelog Demonstrates the updated syntax for registering plugins, specifically the Pinia ORM Axios plugin, in version 1.10.0. This change affects how plugins are passed during ORM initialization. ```javascript - const piniaOrm = createORM() - piniaOrm().use(createPiniaOrmAxios({ - axios, - })) + const piniaOrm = createORM({ + plugins: [ + createPiniaOrmAxios({ + axios, + }), + ], + }) ``` -------------------------------- ### find() Method Usage Source: https://pinia-orm.codedredd.de/api/query/find Demonstrates how to use the find() method to retrieve a single user by ID or multiple users by an array of IDs. ```APIDOC ## `find()` ### Description Retrieves a record by its ID or multiple records by an array of IDs. ### Method Signature ```typescript function find(id: string | number): Item function find(ids: (string | number)[]): Collection ``` ### Usage Examples ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' const userRepo = useRepo(User) // Find a single user by ID console.log(userRepo.find(1)) // Returns a single User model or null // Find multiple users by an array of IDs console.log(userRepo.find([1, 2, 5])) // Returns an array of User models ``` -------------------------------- ### Fetch All Posts with Pinia ORM Source: https://pinia-orm.codedredd.de/guide/getting-started/what-is-pinia-orm Retrieve all posts using the `all` method from the repository. This fetches the base data for the posts entity. ```javascript // Fetch all posts. const posts = useRepo(Post).all() /* [ { id: 1, body: '.....' }, { id: 2, body: '.....' } ] */ ``` -------------------------------- ### Array Cast Example Source: https://pinia-orm.codedredd.de/api/model/options/casts Use ArrayCast to ensure a field is treated as an array. This is useful for fields like 'meta' that might contain array data. ```javascript import { Model } from 'pinia-orm' import { ArrayCast } from 'pinia-orm/casts' class User extends Model { static entity = 'users' static fields() { return { id: this.attr(null), meta: this.attr({}) } } static casts() { return { meta: ArrayCast } } } ``` -------------------------------- ### Instance Properties Source: https://pinia-orm.codedredd.de/plugins/axios/api/request Properties available on the Request instance. ```APIDOC ## Instance Properties ### `model` * **Type** : `typeof Model` The model class that is attached to the Request instance. ### `axios` * **Type** : `AxiosInstance` The axios instance that will be used to perform the request. ``` -------------------------------- ### Define Adult Entity with baseEntity Source: https://pinia-orm.codedredd.de/api/model/options/base-entity Example of defining an 'Adult' entity that inherits from 'Person' using the `baseEntity` option. This is useful for Single Table Inheritance. ```javascript class Adult extends Person { static entity = 'adult' static baseEntity = 'person' static fields () { return { ...super.fields(), job: this.attr('') } } } ``` -------------------------------- ### Call a Custom Fetch Action Source: https://pinia-orm.codedredd.de/plugins/axios/guide/custom-actions Invoke the predefined 'fetch' custom action on the User model's API instance. This performs a GET request to '/api/users'. ```javascript useAxiosRepo(User).api().fetch() ``` -------------------------------- ### Static Methods Source: https://pinia-orm.codedredd.de/plugins/axios/api/repository These are static methods available on the Model object for interacting with the repository and setting up Axios. ```APIDOC ## Static Methods ### `api` * `api(): Request` Return a newly created Request instance. ### `setAxios` * `setAxios(axios: AxiosInstance): void` Set the axios instance manually. Typical setups will configure the axios instance during installation. However, in some cases (mostly with Nuxt), you may need to set the axios instance at a later stage. ::: warning IMPORTANT If you omit the axios instance during installation, it's important that one is set using `setAxios` before any attempt to make an API request. ::: **See also** : Nuxt.js Integration ``` -------------------------------- ### Get Cache Instance - Pinia ORM Source: https://pinia-orm.codedredd.de/api/repository/cache Use this to retrieve the cache instance for a specific model's repository. Ensure the model and repository are correctly imported. ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' // Returns the cache instance useRepo(User).cache() ``` -------------------------------- ### Eager Loading Relationships with `with()` Source: https://pinia-orm.codedredd.de/api/query/with Demonstrates how to use the `with()` method to eager load the 'comments' relationship for users. It also shows how to use a closure to filter the loaded comments based on a condition. ```APIDOC ## `with()` ### Description Eagerly loads a specified relationship for the query. ### Method `with(name: string, callback: EagerLoadConstraint = () => {}): Query` ### Parameters - **name** (string) - Required - The name of the relationship to eager load. - **callback** (EagerLoadConstraint) - Optional - A closure that can be used to apply constraints to the eager loaded relationship. ### Request Example ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' const userRepo = useRepo(User) // Eager load 'comments' relationship const usersWithComments = userRepo.with('comments').get() // Eager load 'comments' relationship with a closure to filter active comments const usersWithCommentsOnlyActive = userRepo.with('comments', (query) => { query.where('active', true) }).get() ``` ### Response - **Query** - Returns the Query instance for chaining. ``` -------------------------------- ### Define User Model with HasMany Relationship Source: https://pinia-orm.codedredd.de/guide/relationships/getting-started Define a `User` model with a `hasMany` relationship to `Post`. This setup is used for demonstrating nested data insertion and updates. ```javascript class User extends Model { static entity = 'users' static fields () { return { id: this.attr(null), name: this.string(''), posts: this.hasMany(Post, 'userId') } } } ``` -------------------------------- ### new() Method Source: https://pinia-orm.codedredd.de/api/repository/new Creates a new model instance. By default, it fires `creating` and `saving` hooks, and `created` and `saved` hooks if persisted. Use `make()` to create a model without firing hooks. ```APIDOC ## new(persist = true): Model | null ### Description Creates a new model instance. This method will fire the `creating` and `saving` hooks. Also the `created` and `saved` hooks if it is persisted. If you want to create a new model without firing the hooks use `make()`. ### Parameters * **persist** (boolean) - Optional - Determines whether the new model should be persisted. Defaults to `true`. ### Usage ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' const userRepo = useRepo(User) // Create a new model with default values which will be persisted userRepo.new() // Create a new model with default values which will not be persisted userRepo.new(false) ``` ### Returns * **Model | null**: A new model instance if successful, otherwise null. ``` -------------------------------- ### whereDoesntHave() Usage Source: https://pinia-orm.codedredd.de/api/query/where-doesnt-have Demonstrates how to use the `whereDoesntHave` method to retrieve records that do not have a specified relationship. It includes an example of filtering posts that do not have any comments associated with a particular user. ```APIDOC ## `whereDoesntHave()` ### Description Filters records that do not have a specified relationship. This is useful for finding entities that lack a certain association, such as posts without comments. ### Method Signature ```typescript function whereDoesntHave( relation: string, callback: EagerLoadConstraint = () => {} ): Query ``` ### Parameters - **relation** (string) - Required - The name of the relationship to check for. - **callback** (function) - Optional - A callback function to apply constraints to the relationship query. ### Usage Example ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' import Post from './models/Post' const userRepo = useRepo(User) // Retrieve all posts that dont have comments from userId 1. useRepo(Post).whereDoesntHave('comments', (query) => { query.where('userId', 1) }).get() ``` ### Related Methods - `useCache()`: Cache the query result. - `whereHas()`: Add a "where has" clause to the query. ``` -------------------------------- ### Define Model with `piniaOptions` Source: https://pinia-orm.codedredd.de/api/model/options/pinia-options Use `piniaOptions` to enable persistence for a model. This configuration is set directly on the model class. ```javascript class User extends Model { static entity = 'users' static fields () { return { userId: this.attr(null) } } static piniaOptions = { persist: true } } ``` -------------------------------- ### Eagerly Load All Relations with `withAll()` Source: https://pinia-orm.codedredd.de/api/query/with-all Use `withAll()` to load all relationships for a model. Provide a closure to filter relations or apply constraints. ```javascript import { useRepo } from 'pinia-orm' import User from './models/User' const userRepo = useRepo(User) const usersWithComments = userRepo.withAll().get() // User[] with all its relations loaded // with closure const usersWithCommentsOnlyActive = userRepo.withAll((query) => { query.where('active', true) }).get() // User[] with comments which are active. Don't forget that you still get all Users just with less relations ```