Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: adding api server support for read methods #33

Merged
merged 6 commits into from
Aug 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions docs/advanced/fetching-indexed-data.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import TOCInline from '@theme/TOCInline';

# Fetching Indexed Data
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the error with the build is because you need to import the components:

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import TOCInline from '@theme/TOCInline';

# Fetching Indexed Data

<TOCInline
  maxHeadingLevel={4}
  toc={toc}
/>

## Overview


## Overview

The `index` function in the Social SDK allows you to retrieve indexed values based on specified criteria from the Social API server. This function is crucial for efficient lookups of social interactions or custom indexed data, supporting various filtering, ordering, and pagination options.

:::note

The `index` function is only available through the API server and does not have an RPC version.

:::

## Function Signature

```typescript
public async index({
action,
key,
accountId,
order,
limit,
from,
}: IIndexOptions): Promise<Record<string, unknown>>
```

### Parameters

- `action`: The index_type from the standard (e.g., 'like' in the path 'index/like').
- `key`: Can be either a string or an object:
- If string: The inner indexed value from the standard.
- If object: Can include properties like type, path, and blockHeight.
- `accountId` (optional): A string or array of account IDs to filter values.
- `order` (optional): The order of results. Either 'asc' or 'desc'. Default is 'asc'.
- `limit` (optional): The number of values to return. Default is 100.
- `from` (optional): The starting point for fetching results. Defaults to 0 or Max depending on order.

### Return Value

A promise that resolves to an array of matched indexed values, ordered by blockHeight.

## Usage Examples

### Basic Usage

<Tabs
defaultValue="javascript-via-package-manager"
values={[
{ label: 'JavaScript (via package manager)', value: 'javascript-via-package-manager' },
{ label: 'JavaScript (via CDN)', value: 'javascript-via-cdn' },
{ label: 'TypeScript', value: 'typescript' },
]}>
<TabItem value="javascript-via-package-manager">

```js
const { Social } = require('@builddao/near-social-js');

const social = new Social();
const result = await social.index({
action: 'like',
key: 'post-123',
});

console.log(result);
```

</TabItem>
<TabItem value="javascript-via-cdn">

```js
var social = new NEARSocialSDK();

social.index({
action: 'like',
key: 'post-123',
}).then((result) => {
console.log(result);
});
```

</TabItem>
<TabItem value="typescript">

```typescript
import { Social } from '@builddao/near-social-js';

const social = new Social();
const result = await social.index({
action: 'like',
key: 'post-123',
});

console.log(result);
```

</TabItem>
</Tabs>

### Advanced Usage

You can use additional options to customize the behavior of the `index` function:

```typescript
const result = await social.index({
action: 'follow',
key: 'alice.near',
accountId: ['bob.near', 'charlie.near'],
order: 'desc',
limit: '50',
from: 100,
});
```

This example retrieves the last 50 'follow' actions for 'alice.near', starting from the 100th most recent entry, and only includes actions by 'bob.near' and 'charlie.near'.

## Use Cases

The `index` function is particularly useful for:

1. Fetching all 'like' actions for a specific post:
```typescript
const likes = await social.index({
action: 'like',
key: {
type: 'social',
path: 'efiz.near/post/main',
blockHeight: 124692995,//blockHeight of the post
},
});
```

2. Retrieving recent 'follow' actions for a user:
```typescript
const result = await social.index({
action: 'graph',
key: 'follow',
order: 'desc',
accountId: 'alice.near',
limit: '10',
});
```

3. Querying custom indexed data based on application-specific schemas:
```typescript
const customData = await social.index({
action: 'custom-action',
key: 'app-specific-key',
});
```

By leveraging the `index` function, you can build efficient and scalable features in your NEAR Social applications, such as activity feeds, trending content algorithms, or custom data aggregations.

:::tip

Combine the `index` function with `get` and `keys` for comprehensive data retrieval strategies in your application.

:::
1 change: 1 addition & 0 deletions docs/advanced/index.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Advanced

* [Reading Data](advanced/reading-data)
* [Fetching Indexed Data](advanced/fetching-indexed-data)
* [Storing Data](advanced/storing-data)
* [Granting Write Permission](advanced/granting-write-permission)
* [Storage Deposit/Withdrawal](advanced/storage-deposit-withdraw)
139 changes: 138 additions & 1 deletion docs/advanced/reading-data.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@ import TOCInline from '@theme/TOCInline';

# Reading Data

The Social SDK provides two main functions for reading data: `get` and `keys`. Both functions now support API server requests for improved performance on mainnet, as well as direct contract calls.

<TOCInline
maxHeadingLevel={4}
toc={toc}
/>

# Get Function

## Overview

Reading data is referenced by a set of key paths, where each path corresponds to the object to return.
The get function in the Social SDK allows you to read data referenced by a set of key paths, where each path corresponds to the object to return. This function now supports both direct contract calls and API server requests for improved performance on mainnet.

:::note

Expand Down Expand Up @@ -257,3 +261,136 @@ The [`get`](../api-reference/social#getoptions) function also supports wildcard

</TabItem>
</Tabs>

## Using API Server (Default)
By default, the get function uses the API server for improved performance on mainnet. You don't need to specify any additional parameters for this behavior.
This is only for mainnet.


## Using Direct Contract Calls
If you want to make direct contract calls instead of using the API server, you can set useApiServer to false:
```typescript
const result = await social.get({
keys: ['alice.near/profile/**'],
useApiServer: false,
});
```
Note that when using direct contract calls, you can use the withNodeId option, which is not available when using the API server.


# Keys Function

## Overview

The `keys` function allows you to retrieve a list of keys that match specified criteria. This is useful for querying the data structure without necessarily reading all the associated values.

## Usage Examples

### Basic Usage

<Tabs
defaultValue="javascript-via-package-manager"
values={[
{ label: 'JavaScript (via package manager)', value: 'javascript-via-package-manager' },
{ label: 'JavaScript (via CDN)', value: 'javascript-via-cdn' },
{ label: 'TypeScript', value: 'typescript' },
]}>
<TabItem value="javascript-via-package-manager">

```js
const { Social } = require('@builddao/near-social-js');

const social = new Social();
const result = await social.keys({
keys: [
'alice.near/profile/**',
'bob.near/post/**',
],
});

console.log(result);
```

</TabItem>
<TabItem value="javascript-via-cdn">

```js
var social = new NEARSocialSDK();

social.keys({
keys: [
'alice.near/profile/**',
'bob.near/post/**',
],
}).then((result) => {
console.log(result);
});
```

</TabItem>
<TabItem value="typescript">

```typescript
import { Social } from '@builddao/near-social-js';

const social = new Social();
const result = await social.keys({
keys: [
'alice.near/profile/**',
'bob.near/post/**',
],
});

console.log(result);
```

</TabItem>
</Tabs>

### Using API Server (Default)

By default, the `keys` function uses the API server for improved performance on mainnet. You don't need to specify any additional parameters for this behavior.

### Using Direct Contract Calls

If you want to make direct contract calls instead of using the API server, you can set `useApiServer` to `false`:

```typescript
const result = await social.keys({
keys: ['alice.near/profile/**'],
useApiServer: false,
});
```

### Additional Options

You can use additional options to customize the behavior of the `keys` function:

```typescript
const result = await social.keys({
keys: ['alice.near/profile/**'],
blockHeight: 12345678,
returnDeleted: true,
returnType: 'History',
valuesOnly: true,
});
```

This example retrieves keys at a specific block height, includes deleted keys, returns historical data, and only includes values in the response.

:::note

The `returnType` option with value "History" is only supported when using the API server (`useApiServer: true`).

:::

## Use Cases

The `keys` function is particularly useful for:

1. Discovering available data structures without fetching all the associated values.
2. Checking for the existence of certain keys or patterns in the data.
3. Retrieving metadata about keys, such as when they were last updated or deleted.
4. Efficiently querying large data sets by first fetching keys and then selectively retrieving values.

By combining the `get` and `keys` functions, you can build powerful and efficient data retrieval strategies for your NEAR Social applications.
38 changes: 37 additions & 1 deletion docs/api-reference/social.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,50 @@ import TOCInline from '@theme/TOCInline';

| Name | Type | Required | Default | Description |
|---------|------------------------------------|----------|---------|-----------------------------------------------------|
| options | [`IGetOptions`](types#igetoptions) | yes | - | Options that include the rpc url and a set of keys. |
| options | [`IGetOptions`](types#igetoptions) | yes | - | Options that include the set of keys. |

#### Returns

| Type | Description |
|-------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `Promise<object>` | A promise that resolves to an object with the top-level properties referencing the keys and the nested properties/objects referencing the corresponding path. |

### `keys(options)`
> Retrieves a list of keys that match specified criteria.
> This function is useful for querying the data structure without necessarily reading all the associated values.
> For example:
> * `alice.near/profile/**` - will match all keys under the profile of account `alice.near`.
> * `*/post/*` - will match all post keys for all accounts.
> * `bob.near/widget/***` - will match all widget keys and their nested keys for account `bob.near`.

#### Parameters
| Name | Type | Required | Default | Description |
|---------|--------------------------------------|----------|---------|-----------------------------------------------------|
| options | [`IKeysOptions`](types#ikeysoptions) | yes | - | Options that specify the criteria for key retrieval. |

#### Returns
| Type | Description |
|-------------------|---------------------------------------------------------------------------------------------------------------|
| `Promise<object>` | A promise that resolves to an object containing the matching keys and their metadata, ordered by block height. |

### `index(options)`
> Retrieves indexed values based on specified criteria from the Social API server.
> This function is crucial for efficient lookups of social interactions or custom indexed data.
> For example:
> * Fetching all 'like' actions for a specific post.
> * Retrieving recent 'follow' actions for a user.
> * Querying custom indexed data based on application-specific schemas.

#### Parameters
| Name | Type | Required | Default | Description |
|---------|----------------------------------------|----------|---------|-----------------------------------------------------|
| options | [`IIndexOptions`](types#iindexoptions) | yes | - | Options that specify the criteria for index retrieval. |

#### Returns
| Type | Description |
|-------------------|---------------------------------------------------------------------------------------------------------------|
| `Promise<object>` | A promise that resolves to an array of matched indexed values, ordered by block height. |

### `getVersion()`

> Gets the current version of the social contract.
Expand Down
Loading