Skip to content

Exports

Jiří Čermák edited this page Dec 6, 2022 · 16 revisions

@ackee/petrus - v6.0.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 Action Creator Functions

Redux Saga Functions

Redux Selector Functions

Utilities Functions

Type Aliases

ApiKey

Ƭ ApiKey: "fetchUser" | "login" | "logout" | "refreshTokens" | "retrieveTokens"

Defined in

src/constants/index.ts:22


PetrusCredentials

Ƭ PetrusCredentials: ConfigurePetrusCredentials extends { value: unknown } ? ConfigurePetrusCredentials["value"] : void

Defined in

src/types/index.ts:32


PetrusLogger

Ƭ PetrusLogger: Object

Type declaration

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

Defined in

src/types/index.ts:63


PetrusOAuth

Ƭ PetrusOAuth: Object

Type declaration

Name Type
searchParams Record<string, any>

Defined in

src/types/index.ts:59


PetrusTokens

Ƭ PetrusTokens: ConfigurePetrusTokens extends { value: Tokens } ? ConfigurePetrusTokens["value"] : Tokens

Defined in

src/types/index.ts:50


PetrusUser

Ƭ PetrusUser: ConfigurePetrusUser extends { value: unknown } ? ConfigurePetrusUser["value"] : any

Defined in

src/types/index.ts:30

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.

example

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

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

Defined in

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


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


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

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

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


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


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


loginReset

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

Defined in

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

Configure Functions

configure

configure(customConfig): Object

example

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

  type RootState = ReturnType<typeof rootReducer>;

  declare module '@ackee/petrus' {
          interface ConfigurePetrusCredentials {
              value: Credentials;
          }

          interface ConfigurePetrusUser {
              value: UserInfo;
          }

          interface ConfigurePetrusAppRootState {
              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: Required<PetrusTokens>) {
              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

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


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 Action Creator Functions

loginRequest

loginRequest(payload): Object

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
     }
   }
})

Parameters

Name Type
payload void

Returns

Object

Name Type
payload undefined
type "@@petrus/LOGIN_REQUEST"

Defined in

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


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

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

accessTokenSelector

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

Parameters

Name Type
state any

Returns

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

Defined in

src/services/selectors/tokens.ts:17


apiSelector

apiSelector(state, apiKey): ApiState

example

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

const fetchUserSelector = createSelector(apiSelector, api => api.fetchUser);

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

Parameters

Name Type
state any
apiKey ApiKey

Returns

ApiState

Defined in

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

src/services/selectors/entities.ts:21


tokensPersistenceSelector

tokensPersistenceSelector(state): TokensPersistence

Parameters

Name Type
state any

Returns

TokensPersistence

Defined in

src/services/selectors/tokens.ts:12


tokensSelector

tokensSelector(state): null | Tokens

Parameters

Name Type
state any

Returns

null | Tokens

Defined in

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

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


isPetrusError

isPetrusError(error): error is PetrusError<Error>

TS type guard function for PetrusError.

Parameters

Name Type
error unknown

Returns

error is PetrusError<Error>

Defined in

src/config/index.ts:59

@ackee/petrus - v6.0.0

Clone this wiki locally