Skip to content

Commit

Permalink
Merge pull request #8 from dgoemans/feature/Auth
Browse files Browse the repository at this point in the history
Authorization and errors
  • Loading branch information
dgoemans authored Dec 28, 2020
2 parents 2d6a8b0 + c877489 commit f851a9b
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 11 deletions.
7 changes: 1 addition & 6 deletions __tests__/__snapshots__/command-query.test.ts.snap
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`spot Adds errors when the fetch fails 1`] = `
Object {
"message": "invalid json response body at reason: Unexpected token < in JSON at position 0",
"type": "invalid-json",
}
`;
exports[`spot Adds errors when the fetch fails 1`] = `"FetchError: invalid json response body at reason: Unexpected token < in JSON at position 0"`;
28 changes: 28 additions & 0 deletions __tests__/command-query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ interface DataType {
let users: { [k: string]: User } = {};

const baseUrl = 'http://example.com';
const authToken = 'AUTH_TOKEN';

const waitForLoadingDone = (spot: Spot<DataType>) => new Promise(spot.subscribeOnce);

Expand Down Expand Up @@ -79,6 +80,17 @@ describe('spot', () => {
status: 200,
body: '',
};
} if (req.url.startsWith(`${baseUrl}/authorized-endpoint`)) {
if (req.headers.get('authorization') === authToken) {
return {
body: '{}',
status: 200,
};
}
return {
body: 'NOT AUTHORIZED',
status: 401,
};
}
return {
status: 404,
Expand Down Expand Up @@ -224,4 +236,20 @@ describe('spot', () => {
expect(spot.data.users['id-two']).toMatchObject({ age: 3, name: 'Rufus', role: 'Home Security' });
expect(spot.data.users['id-one']).toMatchObject({ age: 7, name: 'Spot', role: 'Good Boy' });
});

it('Inserts authorization headers data', async () => {
const spot = initializeSpot<DataType>(baseUrl);

await spot.query('authorized-endpoint', {}, ['auth'], { authorization: 'WRONG TOKEN' });
expect(spot.errors).toHaveLength(1);
expect(spot.errors[0]).toBe('Error: QUERY FAILED 401: Unauthorized');

await spot.query('authorized-endpoint', {}, ['auth'], { authorization: authToken });
const successResult = {
auth: {},
loading: false,
};

expect(spot.data).toMatchObject(successResult);
});
});
14 changes: 11 additions & 3 deletions src/fetch-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ export const fetchMiddleware = (api: MiddlewareAPI) => (next: Dispatch) => async
const response = await fetch(url, {
...defaultFetchConfig,
method: action?.config?.method ?? 'GET',
headers: {
...defaultFetchConfig.headers,
authorization: action.config?.authorization || '',
},
});

if (response.status < 200 || response.status >= 400) {
Expand Down Expand Up @@ -56,10 +60,10 @@ export const fetchMiddleware = (api: MiddlewareAPI) => (next: Dispatch) => async
correlationId,
},
});
} catch (e) {
} catch (err) {
// eslint-disable-next-line no-console
console.error(e);
api.dispatch({ type: 'ERROR', payload: e, metadata: { correlationId } });
console.error(err);
api.dispatch({ type: 'ERROR', payload: err.toString(), metadata: { correlationId } });
} finally {
api.dispatch({ type: 'STATE_UPDATED', metadata: { correlationId } });
}
Expand All @@ -76,6 +80,10 @@ export const fetchMiddleware = (api: MiddlewareAPI) => (next: Dispatch) => async
...defaultFetchConfig,
method: action?.config?.method ?? 'POST',
body: JSON.stringify(action.payload.params),
headers: {
...defaultFetchConfig.headers,
authorization: action.config?.authorization || '',
},
});

if (response.status < 200 || response.status >= 400) {
Expand Down
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export class Spot<T = unknown> {
await this.waitForQuery();
}

command = async (endpoint: string, params: { [k: string]: unknown }, config?: { method?: string }) => {
command = async (endpoint: string, params: { [k: string]: unknown }, config?: ActionConfig) => {
this.store.dispatch({
type: 'COMMAND',
payload: { params, endpoint },
Expand Down Expand Up @@ -103,7 +103,7 @@ export class Spot<T = unknown> {
}

get errors() {
return deepmerge([], this.store.getState().errors);
return [...this.store.getState().errors];
}
}

Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export type ActionType = 'SETUP' | 'ERROR' | 'QUERY' | 'COMMAND' | 'QUERY_COMPLE

export interface ActionConfig {
method?: string;
authorization?: string;
}

export interface Action {
Expand Down

0 comments on commit f851a9b

Please sign in to comment.