-
Notifications
You must be signed in to change notification settings - Fork 48
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
Refactor interceptors as middlewares #72
Merged
Merged
Changes from 19 commits
Commits
Show all changes
34 commits
Select commit
Hold shift + click to select a range
fda6faf
Refactor interceptors as middlewares
djhi c0c6b61
Fix Sinon
djhi af6b6e7
Rename BaseServer classes
djhi 9096436
Add comment
djhi b1a0a00
Cleanup types
djhi 5570922
Add withDelay middleware
djhi 7e8e47e
Fix Sinon integration
djhi 7b97ff8
Fix SinonServer tests
djhi a8d3050
Fix build
djhi d80d993
Update Upgrade Guide
djhi 875b676
Fix upgrade guide
djhi d9a4982
Remove unnecessary sinon html file
djhi 9ed57ce
Use FetchMockServer in example
djhi cb8e5f1
Refactor
djhi 46a7912
Make msw example less verbose
djhi 1ce980d
Remove debug code
djhi 6d39911
Simplify sinon example
djhi e2f4c19
Better server side validation
djhi 3c655d1
Remove unnecessary types
djhi 8662b5e
Make sinon async compatible
djhi c59cce2
Reorganize tests
djhi 7e883eb
Apply review suggestions
djhi 0007f7b
Rename requestJson to requestBody
djhi f96e328
Update comments and readme
djhi b46a393
Simplify and document MSW
djhi 6628014
Rewrite documentation
djhi a98bedd
Update documentation
djhi daf48e4
Don't extend Database
djhi 55c76cb
Revert unnecessary changes
djhi f1c7732
Fix examples middlewares
djhi e0f62b9
Fix exports
djhi e993351
Add configuration section in docs
djhi f6ef7c2
Add concepts
djhi 075ef27
Merge branch 'master' into refactor-interceptors
fzaninotto File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
import { type AuthProvider, HttpError } from 'react-admin'; | ||
import data from './users.json'; | ||
|
||
/** | ||
* This authProvider is only for test purposes. Don't use it in production. | ||
*/ | ||
export const authProvider: AuthProvider = { | ||
login: ({ username, password }) => { | ||
const user = data.users.find( | ||
(u) => u.username === username && u.password === password, | ||
); | ||
|
||
if (user) { | ||
const { password, ...userToPersist } = user; | ||
localStorage.setItem('user', JSON.stringify(userToPersist)); | ||
return Promise.resolve(); | ||
} | ||
|
||
return Promise.reject( | ||
new HttpError('Unauthorized', 401, { | ||
message: 'Invalid username or password', | ||
}), | ||
); | ||
}, | ||
logout: () => { | ||
localStorage.removeItem('user'); | ||
return Promise.resolve(); | ||
}, | ||
checkError: (error) => { | ||
const status = error.status; | ||
if (status === 401 || status === 403) { | ||
localStorage.removeItem('auth'); | ||
return Promise.reject(); | ||
} | ||
// other error code (404, 500, etc): no need to log out | ||
return Promise.resolve(); | ||
}, | ||
checkAuth: () => | ||
localStorage.getItem('user') ? Promise.resolve() : Promise.reject(), | ||
getPermissions: () => { | ||
return Promise.resolve(undefined); | ||
}, | ||
getIdentity: () => { | ||
const persistedUser = localStorage.getItem('user'); | ||
const user = persistedUser ? JSON.parse(persistedUser) : null; | ||
|
||
return Promise.resolve(user); | ||
}, | ||
}; | ||
|
||
export default authProvider; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,19 @@ | ||
import simpleRestProvider from 'ra-data-simple-rest'; | ||
import { fetchUtils } from 'react-admin'; | ||
|
||
export const dataProvider = simpleRestProvider('http://localhost:3000'); | ||
const httpClient = (url: string, options: any = {}) => { | ||
if (!options.headers) { | ||
options.headers = new Headers({ Accept: 'application/json' }); | ||
} | ||
const persistedUser = localStorage.getItem('user'); | ||
const user = persistedUser ? JSON.parse(persistedUser) : null; | ||
if (user) { | ||
options.headers.set('Authorization', `Bearer ${user.id}`); | ||
} | ||
return fetchUtils.fetchJson(url, options); | ||
}; | ||
|
||
export const dataProvider = simpleRestProvider( | ||
'http://localhost:3000', | ||
httpClient, | ||
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,52 @@ | ||
import fetchMock from 'fetch-mock'; | ||
import FakeRest from 'fakerest'; | ||
import { FetchMockServer, withDelay } from 'fakerest'; | ||
import { data } from './data'; | ||
import { dataProvider as defaultDataProvider } from './dataProvider'; | ||
|
||
export const initializeFetchMock = () => { | ||
const restServer = new FakeRest.FetchServer({ | ||
const restServer = new FetchMockServer({ | ||
baseUrl: 'http://localhost:3000', | ||
data, | ||
loggingEnabled: true, | ||
}); | ||
if (window) { | ||
// @ts-ignore | ||
window.restServer = restServer; // give way to update data in the console | ||
} | ||
restServer.init(data); | ||
restServer.toggleLogging(); // logging is off by default, enable it | ||
|
||
restServer.addMiddleware(withDelay(300)); | ||
restServer.addMiddleware(async (request, context, next) => { | ||
if (!request.headers?.get('Authorization')) { | ||
return new Response(null, { status: 401 }); | ||
} | ||
return next(request, context); | ||
}); | ||
restServer.addMiddleware(async (request, context, next) => { | ||
if (context.collection === 'books' && request.method === 'POST') { | ||
if ( | ||
restServer.collections[context.collection].getCount({ | ||
filter: { | ||
title: context.requestJson?.title, | ||
}, | ||
}) > 0 | ||
) { | ||
throw new Response( | ||
JSON.stringify({ | ||
errors: { | ||
title: 'An article with this title already exists. The title must be unique.', | ||
}, | ||
}), | ||
{ | ||
status: 400, | ||
statusText: 'Title is required', | ||
}, | ||
); | ||
} | ||
} | ||
|
||
return next(request, context); | ||
}); | ||
fetchMock.mock('begin:http://localhost:3000', restServer.getHandler()); | ||
}; | ||
|
||
export const dataProvider = defaultDataProvider; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,10 +1,48 @@ | ||
import { setupWorker } from 'msw/browser'; | ||
import { getMswHandlers } from '../src/FakeRest'; | ||
import { HttpResponse } from 'msw'; | ||
import { MswServer, withDelay } from '../src/FakeRest'; | ||
import { data } from './data'; | ||
import { dataProvider as defaultDataProvider } from './dataProvider'; | ||
|
||
export const worker = setupWorker( | ||
...getMswHandlers({ | ||
baseUrl: 'http://localhost:3000', | ||
data, | ||
}), | ||
); | ||
const restServer = new MswServer({ | ||
fzaninotto marked this conversation as resolved.
Show resolved
Hide resolved
|
||
baseUrl: 'http://localhost:3000', | ||
data, | ||
}); | ||
|
||
restServer.addMiddleware(withDelay(300)); | ||
restServer.addMiddleware(async (request, context, next) => { | ||
if (!request.headers?.get('Authorization')) { | ||
throw new Response(null, { status: 401 }); | ||
} | ||
return next(request, context); | ||
}); | ||
|
||
restServer.addMiddleware(async (request, context, next) => { | ||
if (context.collection === 'books' && request.method === 'POST') { | ||
if ( | ||
restServer.collections[context.collection].getCount({ | ||
filter: { | ||
title: context.requestJson?.title, | ||
}, | ||
}) > 0 | ||
) { | ||
throw new Response( | ||
JSON.stringify({ | ||
errors: { | ||
title: 'An article with this title already exists. The title must be unique.', | ||
}, | ||
}), | ||
{ | ||
status: 400, | ||
statusText: 'Title is required', | ||
}, | ||
); | ||
Comment on lines
+31
to
+41
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I still use a |
||
} | ||
} | ||
|
||
return next(request, context); | ||
}); | ||
|
||
export const worker = setupWorker(...restServer.getHandlers()); | ||
|
||
export const dataProvider = defaultDataProvider; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I still use a throw Response here instead of returning an object to test that this still works