soni
v0.0.11
Published
Strategy Oriented Network Interface
Downloads
3
Readme
Strategy Oriented Network Interface
https://www.npmjs.com/package/soni
https://davidwells.io/blog/publishing-flat-npm-packages-for-easier-import-paths-smaller-consumer-bundle-sizes/
https://glebbahmutov.com/blog/subfolders-as-dependencies/
- Does not use cookies anymore, change terminology in options *
Examples
Get products from TCG.Codes after fetching a session token. Once this session token is fetched, store it in cookies and bind it to the headers of outgoing requests.
import React, { useState } from 'react';
import { get } from 'soni/http';
import { http } from 'soni/strategy';
const api = http({
domain: 'https://api.tcg.codes',
cookies: ['session'],
headers: { session: 'token.session' },
strategy: {
validate: store => {
const tokens = store.fetch();
const valid = Boolean(tokens && tokens.session) && tokens.session.length > 0;
return valid;
},
process: async (store) => {
store.flush();
const { json } = await get({ uri: 'https://api.tcg.codes/auth/tokens' });
if (!json.session)
throw new Error('Missing expected property `session` in API response');
store.mutate(json, false);
store.cookify();
}
}});
export default () => {
const intialProducts: any = [];
let [products, setProducts] = useState(intialProducts);
(async () => {
if (products.length) return;
const res = await api.get('/products/codes');
if (res.status === 200)
setProducts(res.json);
})();
return (
<main>
Products: { products.map((p:any,i:number) => <div key={p.ProductId}>{p.Name}</div>) }
</main>
);
};