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 int 1031 custom fetch function #725

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
d2ef2c1
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
9f7d316
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
0701846
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
e67653f
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
3815cde
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
0efa60c
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
e85f071
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
6c36188
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
74ca482
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
4fd8be5
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
4f369e0
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
1d54dee
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
5c372a6
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
213c895
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
3257fd7
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
cee85fa
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
45ee6e1
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
f446ffc
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
f6f9d59
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
9720026
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
6df417e
feat(int-1031): Add customFetch method to Storyblok class
Dec 26, 2023
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
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,36 @@ window.storyblok.on('input', (event) => {
})
```

## customFetch Function

The `customFetch` function is a custom implementation of the fetch API to be used alongside the client's calls. It is designed to handle different types of `BodyInit` in the `SbFetch` methods (`get`, `post`, `put`, `delete`).

### Examples

Here's an example of how to use the `customFetch` function:

```typescript
const client = new StoryblokClient({
accessToken: ACCESS_TOKEN,
oauthToken: OAUTH_TOKEN,
})

// GET request
client
.customFetch(`spaces/${SPACE_ID}/stories`, { method: 'GET' })
.then((response) => console.log(response))
.catch((error) => console.error(error))

// POST request with JSON body
client
.customFetch(`spaces/${SPACE_ID}/stories`, {
method: 'POST',
body: JSON.stringify({ key: 'value' }),
})
.then((response) => console.log(response))
.catch((error) => console.error(error))
```

### Method `Storyblok#get`

With this method you can get single or multiple items. The multiple items are paginated and you will receive 25 items per page by default. If you want to get all items at once use the `getAll` method.
Expand Down
54 changes: 41 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,19 +85,13 @@ class Storyblok {
public constructor(config: ISbConfig, pEndpoint?: string) {
let endpoint = config.endpoint || pEndpoint

if (!endpoint) {
const getRegion = new SbHelpers().getRegionURL
const protocol = config.https === false ? 'http' : 'https'

if (!config.oauthToken) {
endpoint = `${protocol}://${getRegion(config.region)}/${
'v2' as Version
}`
} else {
endpoint = `${protocol}://${getRegion(config.region)}/${
'v1' as Version
}`
}
const getRegion = new SbHelpers().getRegionURL
const protocol = config.https === false ? 'http' : 'https'

if (!config.oauthToken) {
endpoint = `${protocol}://${getRegion(config.region)}/${'v2' as Version}`
} else {
endpoint = `${protocol}://${getRegion(config.region)}/${'v1' as Version}`
}

const headers: Headers = new Headers()
Expand Down Expand Up @@ -160,6 +154,40 @@ class Storyblok {
})
}

public customFetch(url: string, options: RequestInit) {
// Create a new SbFetch instance with the custom fetch function
const customClient = new SbFetch({
baseURL: this.client.baseURL,
headers: this.client.headers,
fetch: (...args: [any]) => fetch(...args),
})

let method
let params
switch ((options.method || 'get').toLowerCase()) {
case 'get':
method = customClient.get.bind(customClient)
params = {} // GET requests typically don't have a body
break
case 'post':
method = customClient.post.bind(customClient)
params = JSON.parse(options.body as string)
break
case 'put':
method = customClient.put.bind(customClient)
params = JSON.parse(options.body as string)
break
case 'delete':
method = customClient.delete.bind(customClient)
params = JSON.parse(options.body as string)
break
default:
throw new Error(`Invalid method: ${options.method}`)
}

return method(`/${url}`, params)
}

public setComponentResolver(resolver: ComponentResolverFn): void {
this.richTextResolver.addNode('blok', (node: ISbNode) => {
let html = ''
Expand Down
4 changes: 2 additions & 2 deletions src/sbFetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ interface ISbFetch {
}

class SbFetch {
private baseURL: string
public baseURL: string
private timeout?: number
private headers: Headers
public headers: Headers
private responseInterceptor?: ResponseFn
private fetch: typeof fetch
private ejectInterceptor?: boolean
Expand Down
82 changes: 82 additions & 0 deletions tests/customFetch.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { expect, test, describe, beforeEach } from 'vitest'
import StoryblokClient from '../'

const generateJibberishWord = (length) => {
const characters = 'abcdefghijklmnopqrstuvwxyz'
let jibberishWord = ''

for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * characters.length)
jibberishWord += characters.charAt(randomIndex)
}

return jibberishWord
}

console.log('env =>', process.env)

describe('define environment variables', () => {
test('Accessing Environment Variables', () => {
const accessToken = process.env.VITE_ACCESS_TOKEN;
const oauthToken = process.env.VITE_OAUTH_TOKEN;
const spaceId = process.env.VITE_SPACE_ID;

expect(accessToken).not.toEqual('');
expect(oauthToken).not.toEqual('');
expect(spaceId).not.toEqual('');
});
})

describe('customFetch', () => {
let client
const url = `spaces/${process.env.VITE_SPACE_ID}/stories`

beforeEach(() => {
client = new StoryblokClient({
oauthToken: process.env.VITE_OAUTH_TOKEN,
})
})

test('should call GET method', async () => {
const response = await client.customFetch(
url,
{
method: 'GET',
body: {},
}
)
expect(response).toHaveProperty('data')
})

test('should call POST method', async () => {
const jibberish = generateJibberishWord(8)
const postObject = {
story: {
name: 'Test',
slug: jibberish,
content: {
component: 'page',
text: 'test',
},
},
}
const response = await client.customFetch(
url,
{
method: 'POST',
body: JSON.stringify(postObject),
}
)
expect(response.data.story.id).toBeTruthy()
})

test('should return an error for invalid method', async () => {
try {
await client.customFetch(url, {
method: 'INVALID',
})
} catch (error) {
expect(error).toHaveProperty('message')
}
})
})
Loading