@mirai/data-sources
v0.2.11
Published
> A naive isomorphic storage manager
Downloads
783
Readme
💾 @mirai/data-sources
A naive isomorphic storage manager
📦 Setup
Add the package in your project:
yarn add @mirai/data-sourcesrequest
This package provides several methods for request data from the internet. Lets check them out:
request()
This method will help you make promisified http requests, you can use these parameters with it:
endpointas the url we want to requestheadersas the configuration for the http headers, by default it is configured as anapplication/json.hostnameas the http/https host we want use in combination withendpointparameter.methodas the http method, by default will beGET.payloadif you want get the server response as payload.timeoutif we want setup a limit time for our request.propsas the extra properties you want use with the request. If it is aPOST/PUTrequest they will be consolidate in a body parameter.
Being a promisified object, it has certain rules for decide when return a resolve or a reject:
- If the request responses with an
http code 400, arejectwill be returned containing the request'spayload. - If the request has not been resolved and it is not possible obtain the type of error, a
500: Something wrong happened. Try againwill be returned.
Default headers are configured to be removable by passing them as undefined in headers object.
import { request } from '@mirai/data-sources';
const json = await request({ endpoint: 'https://mirai.com' }).catch((error) => console.error(error));requestFile()
In the case you need request a file you can use this method, which can receive these parameters:
endpointas the url we want to requesthostnameas the http/https host we want use in combination withendpointparameter.propsas the extra properties you want use with the request.
Because this method wraps the standard object fetch you can extend it with the parameters you could need.
import { requestFile } from '@mirai/data-sources';
const file = await requestFile({
hostname: 'https://mirai.com',
endpoint: '/file?id=1980',
}).catch((error) => console.error(error));setGlobalHostname()
In the case you need use the same hostname in most of your requests you can use this method for define the common value. Internally it will be saved in the storage of the device.
import { setGlobalHostname, request , requestFile } from '@mirai/data-sources';
setGlobalHostname('https://mirai.com');
request({ endpoint: '/order?id=2020' })l
>> https://mirai.com/order?id=2020
requestFile({ endpoint: '/file?id=1980' })l
>> https://mirai.com//file?id=1980setProxy()
In the case you need a most advance solution for your requests, you can use our proxy policy, which follows the rules of common devServer solutions. Here you have an example:
import { setProxy } from '@mirai/data-sources';
setProxy({
'/endpoint': {
changeOrigin: false,
target: 'https://api.dev.mirai/',
},
'/lookandlike': {
changeOrigin: true,
target: 'https://lookandlike.dev.mirai.com/',
},
});With this configuration and in combination with our method request we can get something like this:
request({ endpoint: '/endpoint?order=1980' });
>> https://api.dev.mirai/endpoint?order=1980
request({ endpoint: '/lookandlike?order=1980' });
>> https://lookandlike.dev.mirai.com/?order=1980Storage
The storage class allows you to store data in an isomorphic way and in different ways. You can choose one of the following adapters:
MemoryAdapteruses a memory storage it will be wipe once the app restart.CookieAdapteruses the cookie system of web browsers.LocalAdapteruses the LocalStorage system of web browsers.SessionAdapteruses the SessionStorage system of web browsers.DomainAdapteruses the window object on web browsers and the global object
Here you have a complete CRUD example using the LocalAdapter:
import { Storage, LocalAdapter } from '@mirai/data-sources';
storage = new Storage({ adapter: LocalAdapter });
const key = 'soyjavi';
const value = { email: '[email protected]' };
if (!storage.has(key)) storage.set(key, value);
storage.get(key);
>> { email: '[email protected]' }
storage.remove(key)
storage.get(key);
>> undefinedHow to encrypt your data
In the event that you need to secure your data, you can do it in a very simple way. storage has a secret property which activates the encryption / decryption process of your data. Let's see an example:
import { Storage, LocalAdapter } from '@mirai/data-sources';
storage = new Storage({ adapter: LocalAdapter, secret: '93c6K@hdiCs$#SY3' });
...Store
The Store is a React component wrapping a Context Api and over-vitamin it. Provides a context provider named StoreProvider which stores the state of our store.Instantiating it is very simple, just wrap your application as follows:
const App = () => (
<StoreProvider>
<YourApp>
</StoreProvider>
);After that, you can use the second piece of Store, the hook useStore. Within this hook you will find 4 properties:
historycontains all the mutations already happened in your state value.setthis method helps you to set new values to the state value.removethis method helps you to clean all the state value.valuethe current state value.
Keeping this in mind, obtaining these properties is as simple as:
const Component = () => {
const { history, set, remove, value } = useStore();
return <></>;
};Now let's take an example where one of our components needs to be in sync with a certain Store state property.
const Component = () => {
const {
value: { session },
} = useStore();
useEffect(() => {
console.log('Session changed', session);
}, [session]);
return <></>;
};Now let's set a new value inside store:
const Component = () => {
const {
set,
value: { session },
} = useStore();
return (
<>
<button onClick={() => set({ click: true })} />
</>
);
};dummy //TODO delete
