Skip to content

Queries doc #4

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

Open
wants to merge 4 commits into
base: one
Choose a base branch
from
Open
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
77 changes: 77 additions & 0 deletions technical-guides/talentlayer-subgraph/1-introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Introduction

Welcome to the TalentLayer API documentation. This documentation is intended to help you get started with the TalentLayer API. It is a work in progress and will be updated regularly.

TalentLayer provides querying mechanisms by using the tools provided by [The Graph](https://thegraph.com/en/). The [TalentLayer Subgraph](https://github.com/TalentLayer/talentlayer-id-subgraph) is the implementation of [The Graph](https://thegraph.com/en/) that should be used to query TalentLayer data. The Data that can be queried is defined by [the Subgraph Schema](https://github.com/TalentLayer/talentlayer-id-subgraph/blob/main/schema.graphql) and can be explored using [the GraphQL explorer](https://cloud.hasura.io/public/graphiql).

<br>

---

<br>

## **Exploring the Subgraph**

**Subgraph link**

- [**Polygon Mumbai Testnet**](https://api.thegraph.com/subgraphs/name/talentlayer/talent-layer-mumbai)

- [**Polygon mainnet**](https://api.thegraph.com/subgraphs/name/talentlayer/talentlayer-polygon)

**Playground Link**

To ensure that your queries are working properly before using them in your project, you can use the Graph playgroun below.

- [**Polygon Mumbai playground**](https://thegraph.com/hosted-service/subgraph/talentlayer/talent-layer-mumbai)

- [**Polygon mainnet pLayground**](https://thegraph.com/hosted-service/subgraph/talentlayer/talentlayer-polygon)

Please check the demo video just below <br>
[how test queries with The Graph Playground](https://loom.com/share/a95f65ebe9da4bd1908ca6aacf0b765b)

<br>

---

<br>

## **Using the Playground**

Using the playground you can create and save your own graphQL queries, as well as **try out the default queries that we provide to get you up and running!**

On the righthand side, you have access to some neat functionality that will help you explore the subgraph. Check out **the GraphQL Explorer** as well as **Documentation Explorer** to create customized queries on the fly!

<br>

## **An Introduction to Writing GraphQL Queries for the TalentLayer Subgraph**

The most commonly used entities has a related description entity that stores the off-chain data hosted on [IPFS](https://www.ipfs.com/).

| On-chain Entity | Off-chain Entity |
| --------------- | ------------------- |
| Service | ServiceDescription |
| Proposal | ProposalDescription |
| Review | ReviewDescription |
| User | UserDescription |
| Platform | PlatformDescription |

The off-chain entity that is related to an on-chain entity can be accessed through the field description. Here is an example of what the relationship looks like in GraphQL.

```graphql
{
services {
id
description {
id
}
}
}
```

{% hint style="info" %}
This same pattern can be applied to the other entities by simply changing **services** to either **users, proposals, reviews,** or **platforms.**
{% endhint %}

<br>

> We will see more examples of this how build different queries in the queries example section.
171 changes: 171 additions & 0 deletions technical-guides/talentlayer-subgraph/2-querying-from-application.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
# Querying TalentLayer graph from an Application

## Using GraphQL client

### **AXIOS**

To make a subgraph request, we use Axios. Axios is a library that allows us to send HTTP requests from the browser or Node.js.
You can use Axios (or other libraries) to query the TalentLayer subgraph. You can find the documentation [here](https://axios-http.com/docs/intro)

> We will detail step by step how to query the TalentLayer subgraph using Axios and display the result on the front end

</br>

---

</br>

#### **1 - REQUEST THE SUBGRAPH**

</br>

First we need to set up the process Request (please check the [file](https://github.com/TalentLayer-Labs/indie-frontend/blob/main/src/utils/graphql.ts) to learn more)

```typescript
/* eslint-disable no-console */
import axios from "axios";
import { config } from "../config";

export const processRequest = async (query: string): Promise<any> => {
try {
return await axios.post(config.subgraphUrl, { query });
} catch (err) {
console.error(err);
return null;
}
};
```

This asynchronous function takes a query string as a parameter, sends it as a POST request to a configured subgraph URL using the axios library, and returns the response data. If an error occurs during the request, the error is logged to the console, and the function returns null

</br>

---

</br>

#### **2 - BUILD THE QUERY**

</br>

Now we can use the processRequest function to query the subgraph.
Let's build a query! For example, if you want to get the user informations based on the user id, we can use the following query:

```typescript
export const getUserById = (id: string): Promise<any> => {
const query = `
{
user(id: "${id}") {
id
address
handle
rating
numReviews
updatedAt
createdAt
description {
about
role
name
country
headline
id
image_url
video_url
title
timezone
skills_raw
}
}
}
`;
return processRequest(query);
};
```

You can test multiple queries on the [subgraph playground](https://thegraph.com/hosted-service/subgraph/talentlayer/talentlayer-polygon)
We will detail in the next queries documentation file how to build your own queries and what kinf of data you can get from the TalentLayer subgraph.

</br>

---

</br>

#### **3- BUILD YOU HOOK**

</br>

Now that we have our query, we can use it in a hook to get the user information.

```typescript
import { useState, useEffect } from "react";
import { getUserById } from "../queries/users";
import { IUser } from "../types";

const useUserById = (userId: string): IUser | null => {
const [user, setUser] = useState<IUser | null>(null);

useEffect(() => {
const fetchData = async () => {
try {
const response = await getUserById(userId);
if (response?.data?.data?.user) {
setUser(response.data.data.user);
}
} catch (err: any) {
// eslint-disable-next-line no-console
console.error(err);
}
};
fetchData();
}, [userId]);

return user;
};

export default useUserById;
```

This code defines a custom React hook called **useUserById** , which accepts an **id** parameter and returns a user object or null. It calls the **getUserById** function module to fetch user data by id (detailed just above). If the data is successfully fetched, the user state is updated with the retrieved user object. In case of an error, the error is logged to the console. The custom hook returns the user object, making it easy to use within other components.

Please find the code[here](https://github.com/TalentLayer-Labs/indie-frontend/blob/main/src/hooks/useUserById.ts)

</br>

---

</br>

#### **3- DIPLAY DATA ON THE FRONT END**

</br>

```typescript
// we import the hook
import useUserById from "../hooks/useUserById";

.......
........
.........

// we call the hook and pass the user id as a parameter and we store the object response in a variable
const userDescription = user?.id ? useUserById(user?.id)?.description : null;

.......
........
.........

return (
// we display the data
<p className='text-gray-900 font-medium'>{userDescription?.about}</p>
<p className='text-gray-900 text-xs'>{userDescription?.title}</p>
)

```

Please find the full code [here](https://github.com/TalentLayer-Labs/indie-frontend/blob/main/src/components/UserDetail.tsx)

</br>

> Let's now see how build different querie
88 changes: 88 additions & 0 deletions technical-guides/talentlayer-subgraph/3-queries-examples.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Queries and response examples

## **Querying Services**

#### Querying Services with their related description

Any of the attributes associated with the entities can be queried.&#x20;

```graphql
{
services {
id
createdAt
updatedAt
description {
id
title
about
}
}
}
```

#### Filtering Services Based On Different Attributes

Queries can also be ordered by and limited in number based on the values of different attributes.

```graphql
# Get last 5 opened services with their offchain data for the platform 1
{
services(
orderBy: createdAt
orderDirection: desc
first: 5
where: { status: Opened, platform: "1" }
) {
id
createdAt
updatedAt
status
platform {
id
}
buyer {
id
handle
numReviews
}
description {
id
title
about
startDate
expectedEndDate
keywords_raw
rateToken
rateAmount
}
}
}
```

{% hint style="info" %}
For more information about sorting, pagination, and filtering please check out [The Graph GraphQL API documentation](https://thegraph.com/docs/en/querying/graphql-api/).
{% endhint %}

#### Fulltext Search for ServiceDescription

The TalentLayer Subgraph further offers a fulltext search feature that can be used to make more advanced text searches.&#x20;

The fulltext search allows using operators to query service descriptions based on text. For example, all the services that has a description that contains either the word `hadhat` or the word `development` in the field `title` or in the field `keywords_raw` can be found using the followng query:

```graphql
{
serviceDescriptionSearchRank(text: "hardhat | development") {
title
about
keywords_raw
service {
id
}
}
}
```

{% hint style="info" %}
For more information on which operators are allowed and how to use them, please check out the Graph's [documentations on fulltext search queries](https://thegraph.com/docs/en/querying/graphql-api/#fulltext-search-queries).
{% endhint %}