Skip to content
This repository has been archived by the owner on Jun 1, 2024. It is now read-only.

Commit

Permalink
Feature/client (#52)
Browse files Browse the repository at this point in the history
* change version (#19)

* added check license (#21)

* remove only of it

* fix merge and eslint

* remove yarn-error

* create a BeagleHttpClient

* fix import

* fix review

* fix type error

* fix review

* fix identation

Co-authored-by: Rafael de Melo Silva <[email protected]>
  • Loading branch information
leonardosantiagozup and rafamsilva authored May 18, 2020
1 parent c79ac2d commit a07ad1c
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 7 deletions.
51 changes: 51 additions & 0 deletions __tests__/BeagleHttpClient.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import nock from 'nock'
import beagleHttpClient from "../src/BeagleHttpClient"

describe.only('BeagleHttpClient', () => {
const url = 'http://test.com'

beforeEach(() => {
nock.cleanAll()
})

it('should use window.fetch as default fetch function', async () => {
const path = '/example'
nock(url).get(path).reply(200, { status: 'OK' })
const response = await beagleHttpClient.fetch(url + path, {})
expect(await response.json()).toEqual({ status: 'OK' })
expect(nock.isDone()).toBe(true)
})

it('should use options when fetching content from server', async () => {
const path = '/example';
nock(url, { reqheaders: { test: 'test' } })
.post(path, (body) => body.test).reply(200, { status: 'OK' })
const body = new URLSearchParams()
body.set('test', 'test')
const parametersOptions = { body, headers: { test: 'test' }, method: 'post' }
await beagleHttpClient.fetch(url + path, parametersOptions)
expect(nock.isDone()).toBe(true)
})

it('should use custom fetch function', async () => {
const fetchFunc = jest.fn()
beagleHttpClient.setFetchFunction(fetchFunc)
await beagleHttpClient.fetch(url, {})
expect(fetchFunc).toHaveBeenCalledWith(url, {})
})
})
15 changes: 15 additions & 0 deletions __tests__/BeagleUIView.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,4 +206,19 @@ describe('BeagleUIView', () => {
view.updateWithTree({ sourceTree: tree, shouldRunMiddlewares: false })
expect(listener.mock.calls[0][0]).not.toBe(tree)
})

it('should apply fetchData configuration to HttpClient', async () => {
const path = '/example'
const fetchData = jest.fn()
view = createBeagleView({
baseUrl,
components: {},
middlewares: [middleware],
fetchData
}, '')
await view.updateWithFetch({ path })

const expectedResult = clone(treeA)
expect(fetchData).toHaveBeenCalledWith(baseUrl + path, { "method": "get" })
})
})
4 changes: 2 additions & 2 deletions __tests__/tree-fetching/server.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ describe('Utils: tree fetching (server)', () => {

it('should load from server with headers', async () => {
nock(basePath, { reqheaders: { test: 'test' } }).get(path).reply(200, JSON.stringify(treeA))
const result = await loadFromServer(url, 'get', { test: 'test' })
const result = await loadFromServer(url, 'get', {test: 'test'}, true)
expect(result).toEqual(treeA)
expect(nock.isDone()).toBe(true)
})
Expand All @@ -66,7 +66,7 @@ describe('Utils: tree fetching (server)', () => {
it('should not save cache after loading from server', async () => {
const treeAString = JSON.stringify(treeA)
nock(basePath).get(path).reply(200, treeAString)
await loadFromServer(url, 'get', {}, false)
await loadFromServer(url, 'get', {}, false)
expect(localStorage.setItem).not.toHaveBeenCalled()
expect(nock.isDone()).toBe(true)
})
Expand Down
29 changes: 29 additions & 0 deletions src/BeagleHttpClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { BeagleHttpClient } from './types'

function createBeagleHttpClient(): BeagleHttpClient {
let fetchFn: typeof fetch = fetch

return {
fetch: (...args) => fetchFn(...args),
setFetchFunction: (newFetchFn: typeof fetch) => fetchFn = newFetchFn,
}
}

const beagleHttpClient = createBeagleHttpClient()

export default beagleHttpClient
7 changes: 4 additions & 3 deletions src/BeagleUIView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,20 +32,22 @@ import {
} from './types'
import createURLBuilder from './utils/url-builder'
import createBeagleNavigator from './BeagleNavigator'
import beagleHttpClient from './BeagleHttpClient'
import beagleTabViewMiddleware from './middlewares/tab-view-component'
// import beagleStyleMiddleware from './middlewares/beagle-style'
// import beagleStyleClassMiddleware from './middlewares/beagle-style-class'

const createBeagleView = <Schema>({
baseUrl,
headers,
middlewares = [],
fetchData,
}: BeagleConfig<Schema>, initialRoute: string): BeagleView<Schema> => {
let currentUITree: IdentifiableBeagleUIElement<Schema>
const listeners: Array<Listener<Schema>> = []
const errorListeners: Array<ErrorListener> = []
const urlFormatter = createURLBuilder(baseUrl)
const beagleNavigator: BeagleNavigator = createBeagleNavigator(initialRoute)
if (fetchData) beagleHttpClient.setFetchFunction(fetchData)

function subscribe(listener: Listener<Schema>) {
listeners.push(listener)
Expand Down Expand Up @@ -155,7 +157,6 @@ const createBeagleView = <Schema>({
mode: TreeUpdateMode = 'replace',
) {
const url = urlFormatter.build(params.path, params.baseUrl)
const allHeaders = { ...headers, ...params.headers }
const originalTree = currentUITree

function onChangeTree(loadedTree: BeagleUIElement<Schema>) {
Expand All @@ -174,7 +175,7 @@ const createBeagleView = <Schema>({
onChangeTree,
errorComponent: params.errorComponent,
loadingComponent: params.loadingComponent,
headers: allHeaders,
headers: params.headers,
method: params.method,
shouldShowError: params.shouldShowError,
shouldShowLoading: params.shouldShowLoading,
Expand Down
7 changes: 6 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,17 @@ export type Strategy = (

export type NavigatorType = 'BROWSER_HISTORY' | 'BEAGLE_NAVIGATOR'

export interface BeagleHttpClient {
fetch: typeof fetch,
setFetchFunction: (fetchFn: typeof fetch) => void,
}

export interface BeagleConfig<Schema> {
baseUrl: string,
schemaUrl?: string,
headers?: Record<string, string>,
middlewares?: Array<BeagleMiddleware<Schema>>,
strategy?: Strategy,
fetchData?: typeof fetch,
components: {
[K in ComponentName<Schema>]: any
},
Expand Down
3 changes: 2 additions & 1 deletion src/utils/tree-fetching.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import { BeagleNetworkError, BeagleCacheError } from '../errors'
import { BeagleUIElement, Strategy, HttpMethod, ComponentName } from '../types'
import beagleHttpClient from '../BeagleHttpClient'

type StrategyType = 'network' | 'cache'

Expand Down Expand Up @@ -64,7 +65,7 @@ export async function loadFromServer<Schema>(
let response: Response

try {
response = await fetch(url, { method, headers })
response = await beagleHttpClient.fetch(url, { method, headers })
} catch (error) {
throw new BeagleNetworkError(url, error)
}
Expand Down

0 comments on commit a07ad1c

Please sign in to comment.