Skip to content

Exports

Jiří Čermák edited this page Jun 3, 2022 · 16 revisions

@ackee/petrus - v5.3.6

Table of contents

Enumerations

Interfaces

Type Aliases

Other Variables

Redux Action Creator Variables

Redux Action Creator

Override the default `tokensPersistence` value Variables

Redux Action Type Variables

Redux Selector Variables

HOC Functions

Other Functions

React Component Functions

React Hook Functions

Redux Saga Functions

Redux Selector Functions

Utilities Functions

Type Aliases

PetrusCredentials

Ƭ PetrusCredentials: any

Defined in

src/types/index.ts:16


PetrusLogger

Ƭ PetrusLogger: Object

Type declaration

Name Type
error Console["error"]

Defined in

src/types/index.ts:10


PetrusOAuth

Ƭ PetrusOAuth: Object

Type declaration

Name Type
searchParams Record<string, any>

Defined in

src/types/index.ts:32


PetrusTokens

Ƭ PetrusTokens: Object

Type declaration

Name Type
accessToken { expiration?: string | null ; token: string } & Record<string, any>
refreshToken? { token: string } & Record<string, any>

Defined in

src/types/index.ts:18


PetrusUser

Ƭ PetrusUser: any

Defined in

src/types/index.ts:14


StorageDriver

Ƭ StorageDriver: Object

Type declaration

Name Type
get <Key, Value>(k: Key) => HandlerReturnValue<void | Value>
remove <Key>(k: Key) => HandlerReturnValue<void>
set <Key, Value>(k: Key, v: Value) => HandlerReturnValue<void>

Defined in

src/config/types.ts:3

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

src/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.

Defined in

src/modules/tokens/modules/refreshment/actions/general.ts:12


loginRequest

Const loginRequest: ActionCreatorWithPayload<any, "@@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

src/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

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


setUserWithTokens

Const setUserWithTokens: ActionCreatorWithPreparedPayload<[user: any, tokens: PetrusTokens], { tokens: PetrusTokens ; 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

src/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

src/services/actions/control.ts:14


Redux Action Creator

Override the default `tokensPersistence` value Variables

setTokensPersistence

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

example

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

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

Set tokens persistence dynamically

example

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

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


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

src/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

src/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

src/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

src/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

src/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

src/services/actions/authSession.ts:48


LOGIN_FAILURE

Const LOGIN_FAILURE: "@@petrus/LOGIN_FAILURE"

Triggered on failed login.

Defined in

src/modules/auth-session/actions/login.ts:80


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

src/modules/auth-session/actions/login.ts:73


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

src/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

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


Redux Selector Variables

accessTokenSelector

Const accessTokenSelector: (state: never, ...params: []) => null | { expiration?: null | string ; token: string } & Record<string, any> & OutputSelectorFields<(...args: [null | PetrusTokens]) => { expiration?: null | string ; token: string } & Record<string, any> & { clearCache: () => void }> & { clearCache: () => void }

Defined in

src/services/selectors/tokens.ts:17


tokensPersistenceSelector

Const tokensPersistenceSelector: (state: {}, ...params: []) => TokensPersistence & OutputSelectorFields<(...args: [PetrusEntitiesState<unknown>]) => NONE & { clearCache: () => void } & LOCAL & { clearCache: () => void } & SESSION & { clearCache: () => void }> & { clearCache: () => void }

Defined in

src/services/selectors/tokens.ts:12


tokensSelector

Const tokensSelector: (state: {}, ...params: []) => null | PetrusTokens & OutputSelectorFields<(...args: [PetrusEntitiesState<unknown>]) => PetrusTokens & { clearCache: () => void }> & { clearCache: () => void }

Defined in

src/services/selectors/tokens.ts:7

HOC Functions

authorizable

authorizable(AuthorizableComponent, Firewall, Loader?): (props: any) => Element

High order component that based on current state of the auth reducer renders one of these components:

  • AuthorizableComponent it is rendered only if an authorized user had been fetched (-> state.auth.user)
  • Firewall is rendered if application isn't authorized
  • Loader (optional) is renderer whenever the app can't determinate if it's authorized or not (e.g. when app is loading and it doesn't know yet if tokens are available or not)

deprecated Use Authenticated component instead.

example

import React from 'react';
import { authorizable } from '@ackee/petrus';

const AuthContent = <div>User is logged in</div>;
const Firewall = <div>Please login</div>;
const Loader = <div>Loading...</div>;

const AuthorizedComponent = authorizable(AuthContent, Firewall, Loader);

export default AuthorizedComponent;

Parameters

Name Type Default value
AuthorizableComponent any undefined
Firewall any undefined
Loader () => Element MockAppLoader

Returns

fn

▸ (props): Element

Parameters
Name Type
props any
Returns

Element

Name Type
displayName string

Defined in

src/HOC/authorizable.jsx:32


Other Functions

configure

configure<User, Credentials, AppState>(customConfig): Object

Type parameters

Name Type
User extends unknown = any
Credentials extends unknown = any
AppState extends Record<string, any> = Record<string, any>

Parameters

Name Type
customConfig PetrusCustomConfig<User, Credentials, PetrusConfig<User, Credentials, PetrusLogger>>

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

src/configure/index.ts:11


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

src/components/Authenticated/Authenticated.tsx:35


React Hook Functions

useAuthenticated

useAuthenticated(): FlowType

Returns

FlowType

Defined in

src/hooks/useAuthenticated.ts:8


Redux Saga Functions

getAccessToken

getAccessToken(): Generator<any, null | { expiration?: null | string ; token: string } & Record<string, any>, 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 } & Record<string, any>, unknown>

Defined in

src/services/sagas/getAccessToken.ts:88


retrieveTokens

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

Returns

Generator<any, void, unknown>

Defined in

src/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

src/services/sagas/withAuthSession.ts:40


Redux Selector Functions

apiSelector

apiSelector<AppState>(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);
    // ...
}

Type parameters

Name
AppState

Parameters

Name Type
state AppState
apiKey ApiKeys

Returns

ApiState

Defined in

src/services/selectors/api.ts:21


entitiesSelector

entitiesSelector<AppState, User>(state): PetrusEntitiesState<User>

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);
    // ...
}

Type parameters

Name Type
AppState AppState
User extends unknown = any

Parameters

Name Type
state AppState

Returns

PetrusEntitiesState<User>

Defined in

src/services/selectors/entities.ts:21


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

src/modules/oAuth/utils/createExpirationDate.ts:26

@ackee/petrus - v6.0.0

Clone this wiki locally