npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@mirai/data-sources

v0.1.38

Published

> A naive isomorphic storage manager

Downloads

973

Readme

💾 @mirai/data-sources

A naive isomorphic storage manager

📦 Setup

Add the package in your project:

yarn add @mirai/data-sources

request

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:

  • endpoint as the url we want to request
  • headers as the configuration for the http headers, by default it is configured as an application/json.
  • hostname as the http/https host we want use in combination with endpoint parameter.
  • method as the http method, by default will be GET.
  • payload if you want get the server response as payload.
  • timeout if we want setup a limit time for our request.
  • props as the extra properties you want use with the request. If it is a POST/PUT request 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, a reject will be returned containing the request's payload.
  • If the request has not been resolved and it is not possible obtain the type of error, a 500: Something wrong happened. Try again will 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:

  • endpoint as the url we want to request
  • hostname as the http/https host we want use in combination with endpoint parameter.
  • props as 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=1980

setProxy()

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=1980

Storage

The storage class allows you to store data in an isomorphic way and in different ways. You can choose one of the following adapters:

  • MemoryAdapter uses a memory storage it will be wipe once the app restart.
  • CookieAdapter uses the cookie system of web browsers.
  • LocalAdapter uses the LocalStorage system of web browsers.
  • SessionAdapter uses the SessionStorage system of web browsers.
  • DomainAdapter uses 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);
>> undefined

How 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:

  • history contains all the mutations already happened in your state value.
  • set this method helps you to set new values to the state value.
  • remove this method helps you to clean all the state value.
  • value the 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 })} />
    </>
  );
};

Metrics

The Metricsprovides a context provider named MetricsProvider which swhich provides an abstraction layer of the third-party mixpanel service. Instantiating it is very simple, just wrap your application as follows:


const App = () => (
  <MetricsProvider token={MIXPANEL_TOKEN}>
    <YourApp>
  </MetricsProvider>
);

After that, you can use the second piece of Metrics, the hook useMetrics. Within this hook you will find just one property:

  • track this method helps you to track any kind of event, value, wathever.
  • trackRender same as track but in a non-blocker way, great for first render in components.

Keeping this in mind, obtaining and use this property is as simple as:

const Component = () => {
  const { track, trackRender } = useMetrics();

  useLayoutEffect(() => {
    trackRender('RENDER', { component: 'Component' });
  }, []);

  useEffect(() => {
    track('SESSION', { component: 'Component', session });
  }, [session]);

  return <></>;
};

dummy //TODO delete