### Making a GET Request with o.js in Node.js
Source: https://context7.com/janhommes/o.js/llms.txt
Demonstrates how to initialize the o.js handler with a service URL and perform a GET request to fetch resources. This example uses the TripPinServiceRW as a target.
```javascript
// Node.js example
const oHandler = o('https://services.odata.org/V4/TripPinServiceRW/');
oHandler.get('People').query().then((data) => console.log(data));
```
--------------------------------
### Read (GET) Example
Source: https://github.com/janhommes/o.js/blob/master/README.md
Perform a GET request to retrieve resources, with an optional filter. The response will be the exact user if only one matches, otherwise an array of users. Requires wrapping in an async function or using promises.
```javascript
const response = await o('http://my.url')
.get('User')
.query({$filter: `UserName eq 'foobar'`});
console.log(response); // If one -> the exact user, otherwise an array of users
```
--------------------------------
### Install o.js with npm
Source: https://github.com/janhommes/o.js/blob/master/README.md
Install the o.js package using npm. This command installs the 'odata' package, which is the same as 'o.js'.
```bash
npm install odata
```
--------------------------------
### Usage in Node.js
Source: https://github.com/janhommes/o.js/blob/master/README.md
Require the 'o' function from the 'odata' package in a Node.js environment. This example demonstrates a simple GET request using promises.
```javascript
const o = require('odata').o;
// promise example
o('http://my.url')
.get('resource')
.then((data) => console.log(data));
```
--------------------------------
### Create (POST) Example
Source: https://github.com/janhommes/o.js/blob/master/README.md
Perform a POST request to create a new resource. The data object is sent in the request body. Requires wrapping in an async function or using promises.
```javascript
const data = {
FirstName: "Bar",
LastName: "Foo",
UserName: "foobar",
}
const response = await o('http://my.url')
.post('User', data)
.query();
console.log(response); // E.g. the user
```
--------------------------------
### Delete Example
Source: https://github.com/janhommes/o.js/blob/master/README.md
Perform a DELETE request to remove a resource. Requires wrapping in an async function or using promises.
```javascript
const response = await o('http://my.url')
.delete(`User('foobar')`)
.query();
console.log(response); // The status code
```
--------------------------------
### `OHandler.get(resource?)` — Queue a GET request
Source: https://context7.com/janhommes/o.js/llms.txt
Queues a GET request for a specified resource. Chaining multiple `.get()` calls before executing with `.query()` or `.fetch()` allows for sequential execution of requests, returning an array of results.
```APIDOC
## `OHandler.get(resource?)` — Queue a GET request
### Description
Appends a GET request for the given resource path to the handler's internal queue. Multiple `.get()` calls can be chained before calling `.query()` or `.fetch()` — all queued requests are then executed sequentially and their results returned as an array.
### Parameters
#### Path Parameters
- **resource** (string) - Optional - The resource path to request. If omitted, the request is made to the handler's base URL.
### Query Parameters
- **queryOptions** (object) - Optional - OData query options to append to the request URL.
### Request Example
```typescript
import { o } from 'odata';
const oHandler = o('https://services.odata.org/V4/TripPinServiceRW/');
// Single resource — returns object (not array)
const person = await oHandler.get("People('russellwhyte')").query();
console.log(person.FirstName); // 'Russell'
// Collection — returns array
const people = await oHandler.get('People').query({ $top: 4, $orderby: 'LastName' });
console.log(people.length); // 4
// Multiple chained GETs — returns array of results
const [russell, allPeople] = await oHandler
.get("People('russellwhyte')")
.get('People')
.query({ $top: 2 });
console.log(russell.UserName); // 'russellwhyte'
console.log(allPeople.length); // 2
// Error handling — throws Response on HTTP 4xx/5xx
try {
await oHandler.get("People('nonexistent')").query();
} catch (res) {
console.log(res.status); // 404
}
```
```
--------------------------------
### Update (PATCH) Example
Source: https://github.com/janhommes/o.js/blob/master/README.md
Perform a PATCH request to update an existing resource. The data object contains the fields to update. Requires wrapping in an async function or using promises.
```javascript
const data = {
FirstName: 'John'
}
const response = await o('http://my.url')
.patch(`User('foobar')`, data)
.query();
console.log(response); // The result of the patch, e.g. the status code
```
--------------------------------
### Batch Mixed GET and PATCH Requests with OHandler.batch()
Source: https://context7.com/janhommes/o.js/llms.txt
Demonstrates batching mixed GET and PATCH requests using OHandler.batch(). Setting `oHandler.config.batch.useChangset = true` enables changesets for operations like PATCH. The results array contains status codes for changesets and bodies for GET requests.
```typescript
// Batch with mixed GET and PATCH (using changesets)
oHandler.config.batch.useChangset = true;
const mixed = await oHandler
.patch("Airlines('AA')", { Name: 'American Airlines' })
.get("Airlines('AA')")
.batch();
console.log(mixed[0].status); // 204
console.log(mixed[1].body.Name); // 'American Airlines'
```
--------------------------------
### Read (GET)
Source: https://github.com/janhommes/o.js/blob/master/README.md
Retrieves resources using an HTTP GET request. Supports filtering and other OData query options.
```APIDOC
## GET /resource
### Description
Retrieves resources based on the specified criteria.
### Method
GET
### Endpoint
`/{resource}`
### Parameters
#### Query Parameters
- **$filter** (string) - Optional - OData filter expression.
### Request Example
```javascript
const response = await o('http://my.url')
.get('User')
.query({$filter: `UserName eq 'foobar'`});
console.log(response);
```
### Response
#### Success Response (200)
- **response** (array | object) - If one resource matches, it returns the exact user; otherwise, it returns an array of users.
```
--------------------------------
### Queue GET Request with OHandler.get()
Source: https://context7.com/janhommes/o.js/llms.txt
Appends a GET request for a resource to the handler's queue. Chaining multiple .get() calls before .query() executes them sequentially. Handles single resources (returns object) and collections (returns array). Throws Response on HTTP 4xx/5xx errors.
```typescript
import { o } from 'odata';
const oHandler = o('https://services.odata.org/V4/TripPinServiceRW/');
// Single resource — returns object (not array)
const person = await oHandler.get("People('russellwhyte')").query();
console.log(person.FirstName); // 'Russell'
```
```typescript
import { o } from 'odata';
const oHandler = o('https://services.odata.org/V4/TripPinServiceRW/');
// Collection — returns array
const people = await oHandler.get('People').query({ $top: 4, $orderby: 'LastName' });
console.log(people.length); // 4
```
```typescript
import { o } from 'odata';
const oHandler = o('https://services.odata.org/V4/TripPinServiceRW/');
// Multiple chained GETs — returns array of results
const [russell, allPeople] = await oHandler
.get("People('russellwhyte')")
.get('People')
.query({ $top: 2 });
console.log(russell.UserName); // 'russellwhyte'
console.log(allPeople.length); // 2
```
```typescript
import { o } from 'odata';
const oHandler = o('https://services.odata.org/V4/TripPinServiceRW/');
// Error handling — throws Response on HTTP 4xx/5xx
try {
await oHandler.get("People('nonexistent')").query();
} catch (res) {
console.log(res.status); // 404
}
```
--------------------------------
### Batch Multiple GET Requests with OHandler.batch()
Source: https://context7.com/janhommes/o.js/llms.txt
Combines multiple GET requests into a single HTTP batch request. The endpoint and boundary prefix can be configured via OdataConfig.batch. Each individual response is parsed and returned as { contentId, status, body }.
```typescript
import { o } from 'odata';
const oHandler = o('https://services.odata.org/V4/(S(session))/TripPinServiceRW/', {
headers: { 'If-Match': '*', 'Content-Type': 'application/json' },
});
// Batch multiple GETs into one HTTP request
const results = await oHandler
.get('People')
.get('Airlines')
.batch({ $top: 2 });
console.log(results.length); // 2
console.log(results[0].status); // 200
console.log(results[0].body.length); // 2 (People)
console.log(results[1].body.length); // 2 (Airlines)
```
--------------------------------
### Importing o.js in Different Environments
Source: https://context7.com/janhommes/o.js/llms.txt
Shows how to import the o.js library for use in ESM/TypeScript, CommonJS (Node.js), and browser environments via a script tag. Ensure the correct import method is used based on your project setup.
```typescript
// ESM / TypeScript
import { o } from 'odata';
```
```javascript
// CommonJS (Node.js)
const { o } = require('odata');
```
```html
// Browser script tag (UMD)
//
// window.odata.o('http://my.url').get('resource').query().then(console.log);
```
--------------------------------
### Queue PATCH request with OHandler.patch
Source: https://context7.com/janhommes/o.js/llms.txt
Queues a PATCH request to update an entity with partial data. Can be chained with GET to confirm the update.
```typescript
import { o } from 'odata';
const oHandler = o('https://services.odata.org/V4/(S(session))/TripPinServiceRW/', {
headers: { 'If-Match': '*', 'Content-Type': 'application/json' },
});
// PATCH then GET to confirm the update
const [patchResponse, updated] = await oHandler
.patch("People('russellwhyte')", { FirstName: 'Russ' })
.get("People('russellwhyte')")
.query();
console.log(patchResponse.status); // 204 (No Content)
console.log(updated.FirstName); // 'Russ'
```
--------------------------------
### Retrieve Count Only
Source: https://github.com/janhommes/o.js/blob/master/README.md
To retrieve only the count of a resource, query the `$count` endpoint directly. This is useful for getting the total number of items without fetching the data.
```typescript
oHandler.get('People/$count').query().then((count) => {})
```
--------------------------------
### OHandler.patch
Source: https://context7.com/janhommes/o.js/llms.txt
Queues a PATCH request to update an existing entity with partial data. This method can be chained with GET requests to update and then re-fetch the modified entity in a single sequential operation.
```APIDOC
## `OHandler.patch(resource, body)` — Queue a PATCH request
Queues a PATCH request to update an existing entity with partial data. Can be combined with GET in a single chain to update and then re-fetch the modified entity, all in sequential execution.
### Parameters
- **resource** (string): The resource path to update (e.g., "People('russellwhyte')").
- **body** (object): An object containing the partial data to update.
### Request Example
```typescript
const [patchResponse, updated] = await oHandler
.patch("People('russellwhyte')", { FirstName: 'Russ' })
.get("People('russellwhyte')")
.query();
```
### Response
- **patchResponse**: The raw `Response` object for the PATCH request.
- **updated**: The parsed response data after the update and subsequent GET.
### Response Example
```typescript
console.log(patchResponse.status); // 204 (No Content)
console.log(updated.FirstName); // 'Russ'
```
```
--------------------------------
### o(rootUrl, config?)
Source: https://github.com/janhommes/o.js/blob/master/README.md
Initializes the o.js library. Can be used to set the root URL for requests or provide configuration options.
```APIDOC
## o(rootUrl, config?)
### Description
Initializes the o.js library, setting the base URL for OData requests and optional configuration.
### Parameters
#### Path Parameters
- **rootUrl** (string | URL) - The base URL for OData requests.
- **config** (OdataConfig | any) - Optional configuration object. Can include `rootUrl` for handler-based requests.
### Request Example
```javascript
// Using rootUrl directly
o('http://my.url/some-resource').query().then();
// Using handler with rootUrl in config
const oHandler = o('', { rootUrl: 'http://my.url' });
oHandler.get('some-resource').query().then();
// Merging rootUrl from constructor and config
const oHandler = o('v1', { rootUrl: 'http://my.url' });
// requests http://my.url/v1/some-resource
oHandler.get('some-resource').query().then();
// In browser, using relative path
const oHandler = o('v1');
// requests http://current-url/v1/some-resource
oHandler.get('some-resource').query().then();
```
```
--------------------------------
### Create (POST)
Source: https://github.com/janhommes/o.js/blob/master/README.md
Creates a new resource using an HTTP POST request. Accepts a resource path and a data object.
```APIDOC
## POST /resource
### Description
Creates a new resource.
### Method
POST
### Endpoint
`/{resource}`
### Request Body
- **data** (object) - Required - The data to be sent for creating the resource.
### Request Example
```javascript
const data = {
FirstName: "Bar",
LastName: "Foo",
UserName: "foobar",
}
const response = await o('http://my.url')
.post('User', data)
.query();
console.log(response);
```
### Response
#### Success Response (200)
- **response** (any) - The result of the POST operation, typically the created resource.
```
--------------------------------
### Querying a specific resource
Source: https://github.com/janhommes/o.js/blob/master/README.md
Use the 'o' constructor with a specific resource URL to directly query it. This is an alternative to specifying the resource in the .get() or .post() methods.
```javascript
o('http://my.url/some-resource').query().then();
```
--------------------------------
### `o(rootUrl, config?)` — Initialize an OData handler
Source: https://context7.com/janhommes/o.js/llms.txt
Initializes an OData handler with a root URL and optional configuration. The handler can be reused for multiple requests, which are executed sequentially or as a batch.
```APIDOC
## `o(rootUrl, config?)` — Initialize an OData handler
### Description
Creates and returns an `OHandler` configured with the given root URL and optional `OdataConfig`. The handler is reusable: you can call HTTP-verb methods on it multiple times, queuing requests, then flush them all with `query()`, `fetch()`, or `batch()`. When `rootUrl` is a relative path and `config.rootUrl` is provided, the two are merged into an absolute URL.
### Parameters
#### Path Parameters
- **rootUrl** (string) - Required - The base URL for OData service requests.
#### Query Parameters
- **config** (OdataConfig) - Optional - Configuration object for the OData handler.
- **rootUrl** (string) - Optional - Merged with `rootUrl` if `rootUrl` is relative.
- **headers** (object) - Optional - Default headers to include in requests.
- **onStart** (function) - Optional - Callback function executed when a request starts.
- **onFinish** (function) - Optional - Callback function executed when a request finishes.
- **onError** (function) - Optional - Callback function executed on request error.
### Request Example
```typescript
import { o } from 'odata';
// One-shot chaining (browser or Node.js)
const people = await o('https://services.odata.org/V4/TripPinServiceRW/')
.get('People')
.query({ $top: 3, $filter: "FirstName eq 'Russell'" });
// => [{ UserName: 'russellwhyte', FirstName: 'Russell', ... }]
// Reusable handler with base URL in config
const oHandler = o('', {
rootUrl: 'https://services.odata.org/V4/TripPinServiceRW/',
headers: { 'If-Match': '*', 'Content-Type': 'application/json' },
onStart: (handler) => console.log('Request started', handler.pending),
onFinish: (handler, res) => console.log('Done', res?.status),
onError: (handler, res) => console.error('Error', res),
});
// Reuse handler for multiple independent calls
const airlines = await oHandler.get('Airlines').query({ $top: 5 });
const airports = await oHandler.get('Airports').query({ $top: 5 });
```
```
--------------------------------
### Usage in Browser (Script Tag)
Source: https://github.com/janhommes/o.js/blob/master/README.md
Include the o.js library via a script tag in HTML. The library will be available on the `window.odata` object.
```html