Exports - AckeeCZ/petrus Wiki

@ackee/petrus - v6.0.0-beta.0

Table of contents

Enumerations

Interfaces

Type Aliases

Other Variables

Redux Action Creator Variables

Redux Action Type Variables

Configure Functions

React Component Functions

React Hook Functions

Redux Saga Functions

Redux Selector Functions

Utilities Functions

Type Aliases

PetrusCredentials

Ƭ PetrusCredentials: Petrus.ConfigureCredentials extends { value: unknown } ? Petrus.ConfigureCredentials["value"] : void

Defined in

types/index.ts:21


PetrusLogger

Ƭ PetrusLogger: Object

Type declaration

Name Type
error Console["error"]
warn Console["warn"]

Defined in

types/index.ts:54


PetrusOAuth

Ƭ PetrusOAuth: Object

Type declaration

Name Type
searchParams Record<string, any>

Defined in

types/index.ts:50


PetrusRefreshTokens

Ƭ PetrusRefreshTokens: Required<PetrusTokens>

Defined in

types/index.ts:41


PetrusTokens

Ƭ PetrusTokens: Petrus.ConfigureTokens extends { value: Tokens } ? Petrus.ConfigureTokens["value"] : Tokens

Defined in

types/index.ts:39


PetrusUser

Ƭ PetrusUser: Petrus.ConfigureUser extends { value: unknown } ? Petrus.ConfigureUser["value"] : any

Defined in

types/index.ts:19

Other Variables

storageDrivers

Const storageDrivers: Object

Type declaration

Name Type
indexedDB { get: <Key>(key: Key) => Promise<any> ; remove: <Key>(key: Key) => Promise<void> ; set: <Key, Value>(key: Key, val: Value) => Promise<void | IDBValidKey> }
indexedDB.get [object Object]
indexedDB.remove [object Object]
indexedDB.set [object Object]
resetStorage { get: () => null ; set: () => void ; remove: <Key>(key: Key) => Promise<void> }
resetStorage.get () => null
resetStorage.set () => void
resetStorage.remove [object Object]
sessionStorage { get: <Key>(key: Key) => any ; remove: <Key>(key: Key) => void ; set: <Key, Value>(key: Key, values: Value) => void }
sessionStorage.get [object Object]
sessionStorage.remove [object Object]
sessionStorage.set [object Object]

Defined in

config/index.ts:5


Redux Action Creator Variables

checkAccessTokenExpiration

Const checkAccessTokenExpiration: ActionCreatorWithoutPayload<"@@petrus/CHECK_ACCESS_TOKEN_EXPIRATION">

This action will trigger a saga that checks if the access token is expired. If it's, then the access token is refreshed.

example

import { put } from 'redux-saga/effects';
import { checkAccessTokenExpiration } from '@ackee/petrus';

export function* saga() {
  yield put(checkAccessTokenExpiration());
}

Defined in

modules/tokens/modules/refreshment/actions/general.ts:22


loginRequest

Const loginRequest: ActionCreatorWithoutPayload<"@@petrus/LOGIN_REQUEST"> = login.request

The credentials object is passed to the authenticate handler you've provided in the configure method.

example

import { loginRequest } from '@ackee/petrus';

function* login() {
   yield put(loginRequest({
       email: '[email protected]',
       password: 'password123'
   }))
}

// ...
// in `authenticate` handler:
configure({
    // ...
   handlers: {
   // ...
     authenticate: function* authenticateHandler({ email, password }) {
         // Use the credentials to sign-in user
     }
   }
})

Defined in

modules/auth-session/actions/login.ts:50


logoutRequest

Const logoutRequest: ActionCreatorWithoutPayload<"@@petrus/LOGOUT_REQUEST"> = logout.request

Triggers a user logout flow: tokens are cleared from a persistent storage and any auth. data are cleared from the reducer.

example

  import { put } from 'redux-saga/effects';
  import { logoutRequest } from '@ackee/petrus';

  function* logoutSaga() {
      yield put(logoutRequest());
  }

Defined in

modules/auth-session/actions/logout.ts:35


setTokensPersistence

Const setTokensPersistence: ActionCreatorWithPayload<TokensPersistence, "@@petrus/SET_TOKENS_PERSISTENCE">

example 1. Override the default tokensPersistence value:

import { configure, TokensPersistence } from '@ackee/petrus';

const { saga, reducer } = configure({
    // ...
    initialState: {
        tokensPersistence: TokensPersistence.NONE,
    },
});

example 2. Set tokens persistence dynamically:

import { put } from 'redux-saga/effects';
import { setTokensPersistence, TokensPersistence } from '@ackee/petrus';

function* disableTokensPersistence() {
    yield put(setTokensPersistence(TokensPersistence.NONE));
}

function* enableTokensPersistence() {
    yield put(setTokensPersistence(TokensPersistence.LOCAL));
}

Defined in

modules/tokens/modules/storage/actions/index.ts:40


setUserWithTokens

Const setUserWithTokens: ActionCreatorWithPreparedPayload<[user: any, tokens: Tokens], { tokens: Tokens ; user: any }, "@@petrus/SET_USER_WITH_TOKENS", never, never>

If there is available an auth. user and tokens (e.g. from a user sign up), this action will store these data as they would come from the authenticate handler. Thus, the user is signed in without an additional API request required.

Note: If you dispatch this action when a user is already logged in, the logoutRequest action will be first dispatched and then the flow will continue as usual.

example

 import { put } from 'redux-saga/effects';
 import { setUserWithTokens } from '@ackee/petrus';

 function* signUp({ email, password }) {
     const { data } = yield api.post('/auth/sign-up', {
         email,
         password,
     });
     const { user, accessToken, refreshToken, expiration } = data;

     yield put(
         setUserWithTokens(user, {
             accessToken: {
                 token: accessToken,
                 expiration,
             },
             refreshToken: {
                 token: refreshToken,
             },
         }),
     );
 }

Defined in

modules/auth-session/actions/setUserWithTokens.ts:41


terminate

Const terminate: ActionCreatorWithoutPayload<"@@petrus/TERMINATE">

Calls cancel redux saga effect on root Petrus saga and therefore end all infinite loops within. This cancel the saga returned from the configure method.

Defined in

services/actions/control.ts:14


Redux Action Type Variables

ACCESS_TOKEN_AVAILABLE

Const ACCESS_TOKEN_AVAILABLE: "@@petrus/ACCESS_TOKEN_AVAILABLE"

When the access token becomes available, this action is dispatched (on LOGIN_SUCCESS and REFRESH_TOKENS_SUCCESS).

Defined in

services/actions/accessTokenAvailability.ts:28


ACCESS_TOKEN_UNAVAILABLE

Const ACCESS_TOKEN_UNAVAILABLE: "@@petrus/ACCESS_TOKEN_UNAVAILABLE"

Access token becomes unavailable on logout or when tokens refreshment start. It's guaranteed that the ACCESS_TOKEN_UNAVAILABLE action will be dispatched only once after ACCESS_TOKEN_AVAILABLE.

Defined in

services/actions/accessTokenAvailability.ts:35


AUTH_SESSION_END

Const AUTH_SESSION_END: "@@petrus/AUTH_SESSION_END"

The AUTH_SESSION_END action is triggered on AUTH_LOGOUT_SUCCESS or REFRESH_TOKENS_FAILURE.

Defined in

services/actions/authSession.ts:69


AUTH_SESSION_PAUSE

Const AUTH_SESSION_PAUSE: "@@petrus/AUTH_SESSION_PAUSE"

This action is triggered on the access token refreshment start.

Defined in

services/actions/authSession.ts:55


AUTH_SESSION_RESUME

Const AUTH_SESSION_RESUME: "@@petrus/AUTH_SESSION_RESUME"

If access token refreshment was successful, AUTH_SESSION_RESUME is triggered. It's guaranteed it will be dispatched only after AUTH_SESSION_PAUSE action.

Defined in

services/actions/authSession.ts:62


AUTH_SESSION_START

Const AUTH_SESSION_START: "@@petrus/AUTH_SESSION_START"

Once a user has been successfully logged in, this action is dispatched. It's guaranteed that AUTH_SESSION_END must be triggered first before another AUTH_SESSION_START trigger.

example

import { put } from 'redux-saga/effects';
import { AUTH_SESSION_START } from '@ackee/petrus';

function* watchAuthSession() {
    yield takeEvery(AUTH_SESSION_START, function* (action) {
        // ...
    });
}

Defined in

services/actions/authSession.ts:48


LOGIN_FAILURE

Const LOGIN_FAILURE: "@@petrus/LOGIN_FAILURE"

Triggered on failed login.

Defined in

modules/auth-session/actions/login.ts:85


LOGIN_SUCCESS

Const LOGIN_SUCCESS: "@@petrus/LOGIN_SUCCESS"

Triggered on successful login.

example

function* handleLogin() {
   // dispatch login request to '@ackee/petrus'
   yield put(loginRequest({
       email: '[email protected]',
       password: 'supersecret',
   }));

   // wait for the request to resolve
   const result = yield take([LOGIN_SUCCESS, LOGIN_FAILURE]);

   // and then do something (e.g. display login error, redirect user to auth. content)
}

Defined in

modules/auth-session/actions/login.ts:78


RETRIEVE_TOKENS_REQUEST

Const RETRIEVE_TOKENS_REQUEST: "@@petrus/RETRIEVE_TOKENS_REQUEST"

This action is triggered right before tokens retrieval from a local storage begins.

Defined in

modules/tokens/modules/retrieval/actions/index.ts:27


RETRIEVE_TOKENS_RESOLVE

Const RETRIEVE_TOKENS_RESOLVE: "@@petrus/RETRIEVE_TOKENS_RESOLVE"

This action contains payload.tokensRetrieved flag with the tokens retrieval result.

Defined in

modules/tokens/modules/retrieval/actions/index.ts:33


loginReset

Const loginReset: ActionCreatorWithoutPayload<"@@petrus/LOGIN_RESET"> = login.reset

Defined in

modules/auth-session/actions/login.ts:55

Configure Functions

configure

configure(customConfig): Object

link {TODO: link}

example

  interface Credentials {
      email: string;
      password: string;
  }
  interface UserInfo {
      id: string;
      name: string;
  }

  type RootState = ReturnType<typeof rootReducer>;

  declare global {
      namespace Petrus {
          interface ConfigureCredentials {
              value: Credentials;
          }

          interface ConfigureUser {
              value: UserInfo;
          }

          interface ConfigureAppRootState {
              value: BackgroundRootState;
          }
      }
  }

  export const { reducer, saga } = configure({
      selector: state => state.auth,
      handlers: {
          authenticate(credentials: PetrusCredentials) {
              const user: PetrusUser | undefined = {
                  id: '1',
                  name: 'Bob',
              };

              const tokens: PetrusTokens = {
                  accessToken: {
                      token: '...',
                      expiration: '...',
                  },
                  refreshToken: {
                      token: '...',
                  },
              };

              return {
                  user,
                  tokens,
              };
          },
          refreshTokens(tokens: PetrusRefreshTokens) {
              const freshTokens: PetrusTokens = {
                  accessToken: {
                      token: '...',
                      expiration: '...',
                  },
                  refreshToken: {
                      token: '...',
                  },
              };

              return freshTokens;
          },
          getAuthUser(tokens: PetrusTokens) {
              const user: PetrusUser = {
                  id: '1',
                  name: 'Bob',
              };

              return user;
          },
      },
  });

Parameters

Name Type
customConfig PetrusCustomConfig<PetrusConfig>

Returns

Object

Name Type
reducer Reducer<CombinedState<Object>, AnyAction>
saga () => Generator<TakeEffect | CancelEffect | ForkEffect<Generator<AllEffect<Generator<AllEffect<false | Generator<any, void, unknown>>, void, unknown>>, void, unknown>>, void, Task>

Defined in

configure/index.ts:92


React Component Functions

Authenticated

Authenticated(__namedParameters): null | Element

  • children rendered if flowType === FlowType.AUTHENTICATED: valid access token and auth user are available.
  • FallbackComponent rendered if flowType === FlowType.ANONYMOUS: app is unauthorized
  • Loader renderer whenever the app can't determinate if the flowType is FlowType.AUTHENTICATED ir FlowType.ANONYMOUS: authorized or not.

example

import React from 'react';
import { Authenticated } from '@ackee/petrus';
import MyLoginForm from './MyLoginForm';

const MyLoader = () => <div>Loading...</div>;

const MyComponent = () => (
    <Authenticated FallbackComponent={MyLoginForm} LoaderComponent={MyLoader}>
        <div>Private content</div>
    </Authenticated>
);

Parameters

Name Type
__namedParameters AuthenticatedProps

Returns

null | Element

Defined in

components/Authenticated/Authenticated.tsx:35


React Hook Functions

useAuthenticated

useAuthenticated(): FlowType

Returns

FlowType

Defined in

hooks/useAuthenticated.ts:8


Redux Saga Functions

getAccessToken

getAccessToken(): Generator<any, null | { expiration?: null | string ; token: string }, unknown>

Generator function returning PetrusTokens['accessToken'] or null.

example

import { getAccessToken } from '@ackee/petrus';

function* mySaga() {
    const accessToken = yield* getAccessToken();

    console.log(accessToken);
}

Returns

Generator<any, null | { expiration?: null | string ; token: string }, unknown>

Defined in

services/sagas/getAccessToken.ts:88


retrieveTokens

retrieveTokens(): Generator<any, void, unknown>

Returns

Generator<any, void, unknown>

Defined in

modules/tokens/modules/retrieval/sagas/retrieveTokens.ts:88


withAuthSession

withAuthSession<Fn>(task): Generator<any, void, unknown>

A generator function that receives any function as 1st parameter. The provided function will be launched on AUTH_SESSION_START action and cancelled on AUTH_SESSION_END. Note that withAuthSession is a blocking task (if you need to make it non-blocking one, use it with fork effect).

example

import { withAuthSession } from '@ackee/petrus';

function* myAuthSaga() {}

export default function* () {
    yield* withAuthSession(myAuthSaga);
    // non-blocking version: yield fork(withAuthSession, myAuthSaga);
}

Type parameters

Name Type
Fn extends DefaultFn

Parameters

Name Type
task Fn

Returns

Generator<any, void, unknown>

Defined in

services/sagas/withAuthSession.ts:40


Redux Selector Functions

accessTokenSelector

accessTokenSelector(state): null | { expiration?: null | string ; token: string }

Parameters

Name Type
state any

Returns

null | { expiration?: null | string ; token: string }

Defined in

services/selectors/tokens.ts:17


apiSelector

apiSelector(state, apiKey): ApiState

example

import { select } from 'redux-saga/effects';
import { createSelector } from 'reselect';
import { apiSelector, ApiKeys } from '@ackee/petrus';

const fetchUserSelector = createSelector(apiSelector, api => api[ApiKeys.FETCH_USER]);

function* selectFetchUser() {
    const { inProgress, success, error } = yield select(fetchUserSelector);
    // ...
}

Parameters

Name Type
state any
apiKey ApiKeys

Returns

ApiState

Defined in

services/selectors/api.ts:22


entitiesSelector

entitiesSelector(state): PetrusEntitiesState

example

import { select } from 'redux-saga/effects';
import { createSelector } from 'reselect';
import { entitiesSelector } from '@ackee/petrus';

const authUserSelector = createSelector(entitiesSelector, entities => entities.user);

function* selectAuthUser() {
    const authUser = yield select(authUserSelector);
    // ...
}

Parameters

Name Type
state any

Returns

PetrusEntitiesState

Defined in

services/selectors/entities.ts:21


tokensPersistenceSelector

tokensPersistenceSelector(state): TokensPersistence

Parameters

Name Type
state any

Returns

TokensPersistence

Defined in

services/selectors/tokens.ts:12


tokensSelector

tokensSelector(state): null | Tokens

Parameters

Name Type
state any

Returns

null | Tokens

Defined in

services/selectors/tokens.ts:7


Utilities Functions

createExpirationDate

createExpirationDate(expiresIn): null | string

Converts duration in ms to timestamp.

example

import { createExpirationDate } from '@ackee/petrus';

// expiratioDate will be in following format: "2019-02-19T21:02:57.970Z"
const expirationDate = createExpirationDate(3600 * 1000);

// VALID:
createExpirationDate('3600000');
createExpirationDate(null);
createExpirationDate(undefined);

// INVALID:
createExpirationDate('foo');
createExpirationDate('foo123');

Parameters

Name Type Description
expiresIn undefined | null | string | number value in ms when access token expires

Returns

null | string

Access token expiration date in ISO string format.

Defined in

modules/oAuth/utils/createExpirationDate.ts:26

⚠️ **GitHub.com Fallback** ⚠️