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

Update data-sources.mdx (Add for dataSource's initialize method usage) #7931

Open
wants to merge 1 commit into
base: version-2
Choose a base branch
from
Open
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
55 changes: 55 additions & 0 deletions docs/source/data/data-sources.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -368,3 +368,58 @@ class PersonalizationAPI extends RESTDataSource {
return this.progressLoader.load(id);
}
```

### Initialize DataSource

When dataSources are initialized, the initialize method is called. This is useful when you need to initialize the dataSources with the context or cache.

This is the code that initializes the dataSources.

```js
async function initializeDataSources() {
if (config.dataSources) {
const context = requestContext.context;

const dataSources = config.dataSources();

const initializers: any[] = [];
for (const dataSource of Object.values(dataSources)) {
if (dataSource.initialize) {
initializers.push(
dataSource.initialize({
context,
cache: requestContext.cache,
})
);
}
}

await Promise.all(initializers);

if ('dataSources' in context) {
throw new Error(
'Please use the dataSources config option instead of putting dataSources on the context yourself.',
);
}

(context as any).dataSources = dataSources;
}
}
```

If you need to initialize the dataSources with the context or cache, you can use the initialize method.

```js
class InternalApi extends RESTDataSource {
constructor() {
super();
this.baseURL = 'https://internal-api.example.com/';
}

async initialize({ context, cache }) {
this.context = context;
this.cache = cache;
}
}
```