Services

Located in @kiwicom/nitro/lib/services/<service>.

List:

Auth

Contains everything regarding authentication.

Examples:

A fresh setup might look something like:

// ...
import InitAuth from "@kiwicom/nitro/lib/components/InitAuth";
import { Provider as AuthProvider } from "@kiwicom/nitro/lib/services/auth/context";
import type { Brand } from "@kiwicom/nitro/lib/records/Brand";
// ...

const AUTH_COOKIE = "AUTH_TOKEN"; // or whatever you save it as

const brand: Brand = window.__BRAND__;

const handleMyBooking = (token: string) => {
  // redirect the user to MMB
}

const handleRegister = () => {
  // tell the user to check his email
}

const handleSocialAuth = (authURL: string) => {
  // redirect the user to the given URL
}

const handleSignIn = (token: string) => {
  // save the token into cookies as AUTH_COOKIE
}

const handleSignOut = () => {
  // remove AUTH_COOKIE from cookies
}

const NitroProvider = () => (
  <InitAuth
    token={cookies.get(AUTH_COOKIE) || null}
    brand={brand}
    redirectURL={window.location.href} // maybe clean it up from UTMs if needed, or add misc info
    onMyBooking={handleMyBooking}
    onRegister={handleRegister}
    onSocialAuth={handleSocialAuth}
    onSignIn={handleSignIn}
    onSignOut={handleSignOut}
  >
    {auth => (
      <AuthProvider value={auth}>
        <App />
      </AuthProvider>
    )}
  </InitAuth>
);
// ...

You can of course not use the InitAuth component and hook the provider up to your existing setup.

See InitAuth for initializing the service.

Api

Import:

import * as api from "@kiwicom/nitro/lib/services/auth/api";

Types:

declare export function getTokenUser(token: string): Promise<User>;

export type MyBookingInput = {|
  bid: string,
  email: string,
  iata: string,
  departure: Date,
|};

export type OnMyBookingArg = {|
  token: string,
  bid: number,
|};

declare export function getMyBookingToken(input: MyBookingInput): Promise<OnMyBookingArg>;

type LoginInput = {|
  email: string,
  password: string,
  brand: string,
|};

declare export function signIn(input: LoginInput): Promise<AuthUser>;

declare export function logout(token: string): Promise<void>;

export type RegisterInput = {|
  firstName: string,
  lastName: string,
  email: string,
  password: string,
|};

declare export function register(brand: string, input: RegisterInput): Promise<void>;

type SocialAuthProvider = "facebook" | "google";

declare export function socialAuth(provider: SocialAuthProvider, url: string): Promise<string>;

declare export function resetPassword(email: string, brandId: string): Promise<void>;

declare export function getUserFromKWToken(kwAuthToken: string): Promise<AuthUser>;

See types:

Context

Import:

import * as context from "@kiwicom/nitro/lib/services/auth/context";

Types:

type MyBookingInput = {|
  bid: string,
  email: string,
  iata: string,
  departure: Date,
|};

type RegisterInput = {|
  firstName: string,
  lastName: string,
  email: string,
  password: string,
|};

export type Context = {|
  auth: Auth | null,
  loading: boolean,
  onMyBooking: (input: MyBookingInput) => Promise<void>,
  onRegister: (input: RegisterInput) => Promise<void>,
  onSocialAuth: (provider: SocialProvider) => Promise<void>,
  onSignIn: (email: string, password: string) => Promise<void>,
  onSignOut: () => void,
|};

declare var context: React.Context<Context>;

declare export function useAuth(): Context;

export const { Consumer, Provider } = context;

export default context;

See types:

Contains:

Brand

Has all the necessary information regarding branding.

Context

Import:

import * as context from "@kiwicom/nitro/lib/services/brand/context";

Types:

declare var context: React.Context<Brand>;

declare export function useBrand(): Brand;

export const { Consumer, Provider } = context;

export default context;

See types:

Contains the brand configuration object. It is static.

Currency

Has all the necessary information and operations regarding currency.

Setup might look something like:

// Rewrites currencies from fetched to new date structure
import rewriteCurrencies from "@kiwicom/nitro/lib/services/currency/serivces/rewriteCurrencies";

<CurrencyProvider
  value=
>
  {children}
</CurrencyProvider>;

const connector: Connector<OwnProps, Props> = connect(state => ({
  // currency
  currencyId: getCurrency(state),
  available: rewriteCurrencies(getCurrencies(state)),
  recommended: getRecommendedCurrenciesSelectorJS(state)
}));

export default connector(NitroBridge);

See InitCurrency for initializing the service.

Context

Import:

import * as context from "@kiwicom/nitro/lib/services/currency/context";

Types:

export type Context = {|
  currency: Currency,
  available: Currencies,
  recommended: Currency[],
  onChange: (code: string) => void,
|};

declare var context: React.Context<Context>;

declare export function useCurrency(): Context;

export const { Consumer, Provider } = context;

export default context;

See types:

Contains:

GetAll

Import:

import * as getAll from "@kiwicom/nitro/lib/services/currency/getAll";

Types:

export type Module = "search" | "booking" | "mmb";

export type Options = {|
  url?: string,
|};

type Params = {|
  module?: Module,
  options?: Options,
|};

declare export default function getAll(?Params): Promise<FetchedCurrencies>;

See types:

Fetches list of currencies and current rates and combines them.

Init

Import:

import * as init from "@kiwicom/nitro/lib/services/currency/init";

Types:

export type Input = {|
  currencies: Currencies,
  initialCurrency: string,
  countryCurrency: string,
  languageCurrency: string,
  affiliate: string,
  brandCurrencies: string[],
  mostUsedCurrencies?: string[],
|};

export type Payload = {|
  currency: Currency,
  available: Currencies,
  recommended: Currency[],
|};

declare export default function init(input: Input): Payload;

See types:

Resolves actual currency, available and recommended currencies for currency Provider.

Fetch

Contains utilities to be used with the fetch function.

Handlers

Import:

import * as handlers from "@kiwicom/nitro/lib/services/fetch/handlers";

Types:

// Use when you need to handle common API errors, but want the raw response
declare export function handleError(res: Response): Promise<Response>;

// Use when you need to handle common API errors, and the response is a JSON
declare export function handleJSON<T>(res: Response): Promise<T>;

Utility functions for handling fetch responses.

Headers

Import:

import * as headers from "@kiwicom/nitro/lib/services/fetch/headers";

Types:

declare export var JSON_GET: {|
  Accept: string,
|};

declare export var JSON_SEND: {|
  "Content-Type": string,
|};

declare export var JSON_BOTH: {|
  Accept: string,
  "Content-Type": string,
|};

Just utility objects to be used in the headers option when using fetch.

Input

Functions related to normalization, validation and manipulation of input values.

ComposeValidator

Import:

import * as composeValidator from "@kiwicom/nitro/lib/services/input/composeValidator";

Types:

export type Validator = (value: any) => string;

declare export default (...validators: Validator[]) => Validator;

Composes multiple validators into a single validator that returns the first error encountered.

EmailCorrector

Import:

import * as emailCorrector from "@kiwicom/nitro/lib/services/input/emailCorrector";

Types:

declare export default (email: string) => string;

Tries to correct an email, giving you a recommended one back.

Normalizers

Import:

import * as normalizers from "@kiwicom/nitro/lib/services/input/normalizers";

Types:

declare export var email: (value: string) => string;

declare export var numbers: (val: string) => string;

declare export var phone: (val: string) => string;

PhoneValidator

Import:

import * as phoneValidator from "@kiwicom/nitro/lib/services/input/phoneValidator";

Types:

export type Validator = {| error: string, code?: string |}; // "" means no error

declare export function call(phone: string): Promise<FetchedPhone>;

declare export var validate: (val: string) => Promise<Validator>;

See types:

#todo

Validators

Import:

import * as validators from "@kiwicom/nitro/lib/services/input/validators";

Types:

export type Error = string; // "" means no error

declare export var required: (val: mixed) => Error;

declare export var email: (val: string) => Error;

export type YearAfterOpts = {|
  offset: number,
  now: Date,
|};

declare export var yearAfter: (arg: YearAfterOpts) => (val: Date) => Error;

declare export var iata: (val: string) => Error;

declare export var departure: (val: Date, now?: Date) => Error;

declare export var password: (value: string) => Error;

declare export var passwordScore: (value: string, userInput: ?(string[])) => number;

Validators return error translation keys for wrong inputs.

Error is always a string, an empty string means no error.

Intl

TODO

See InitIntl for initializing the service.

Context

Import:

import * as context from "@kiwicom/nitro/lib/services/intl/context";

Types:

export type Context = {|
  ...Intl,
  onDebug: () => void,
|};

declare var context: React.Context<Context>;

declare export function useIntl(): Context;

export const { Consumer, Provider } = context;

export default context;

See types:

Contains all necessary information regarding i18n:

Components for translating:

Translate function

If you need to output a string, not a component, use the translate function located in the context:

<IntlConsumer>
  {({ translate }) => (
    <input
      id={id}
      value={value}
      onChange={onChange}
      placeholder={translate(__("First name"))}
    />
  )}
</IntlConsumer>

Date-fns locale

A promise that resolves to a date-fns locale. Defaults to en-US. To lazy load your own locale, use dynamic import:

const LOCALES = {
  cs: () => import("date-fns/locale/cs"),
  enUS: () => import("date-fns/locale/en-US"),
  ru: () => import("date-fns/locale/ru"),
};

const ID = window.__INTL__.language.id;

const localeFn = LOCALES[ID] || LOCALES.enUS; // Fallback to 'en-US'

<InitIntl raw={intlRaw} getLocale={localeFn()}>
  {intl => (
    <IntlProvider value={intl}>
      <Root />
    </IntlProvider>
  )}
</InitIntl>

Translate

Import:

import * as translate from "@kiwicom/nitro/lib/services/intl/translate";

Types:

export type Values = { [key: string]: string | number };
export type Translate = (key: string, values?: Values) => string;
export type Translations = { [key: string]: string };

declare export default function translate(
  translations: Translations,
  key: string,
  values?: Values,
): string;

Log

TODO

See InitLog for initializing the service.

Api

Import:

import * as api from "@kiwicom/nitro/lib/services/log/api";

Types:

export type Settings = {
  devUrl?: string, // Fires a 2nd, not returned, log call to this URL if supplied
};

declare export default function log(payload: Loglady, settings?: Settings): Promise<void>;

See types:

LogLady API call.

Context

Import:

import * as context from "@kiwicom/nitro/lib/services/log/context";

Types:

export type Context = {|
  log: (event: Event, props: Props) => void,
|};

declare var context: React.Context<Context>;

declare export function useLog(): Context;

export const { Provider, Consumer } = context;

export default context;

See types:

TODO

Globals

Import:

import * as globals from "@kiwicom/nitro/lib/services/log/globals";

Types:

type Static = {|
  brandingId: string,
  UTMs: { [key: string]: string },
  affilParams: { [key: string]: string },
  // Optional
  langId?: string,
  project?: string,
  module?: string,
  pageName?: string,
  deeplinkId?: string,
  pageViewId?: string,
  bid?: number,
  splitster?: { [key: string]: string },
|};

declare export default (statics: Static) => Globals;

See types:

DEPRECATED

Utility for gathering the global object for LogLady tracking.

Uses the window object, use only on the client!

Logger

Import:

import * as logger from "@kiwicom/nitro/lib/services/log/logger";

Types:

export type Statics = {|
  project: string,
  module: string,
  pageName: string,
  langId: string,
  pageViewId: string,
  brandingId: string,
  bid: ?number,
  splitster: { [key: string]: string },
  affilParams: { [key: string]: string },
  UTMs: { [key: string]: string },
|};

declare export var statics: Statics;

export type Settings = {|
  api: ApiSettings,
|};

declare export var settings: Settings;

declare export var getGlobals: () => Globals;

declare export var log: (ev: Event, props: Props) => Promise<void>;
declare export var batch: (evs: EventPayload[]) => Promise<void>;

See types:

A service substituting FE’s current cuckoo.

Setup:

Also exports the getGlobals function that returns globals LogLady expects.

TODO

Context

Import:

import * as context from "@kiwicom/nitro/lib/services/modal/context";

Types:

export type Context = {|
  value: string,
  onChange: (value?: string) => void,
|};

declare var context: React.Context<Context>;

declare export function useModal(): Context;

export const { Consumer, Provider } = context;

export default context;

Holds an information about which modal is currently open. Only supports one modal on purpose.

Initialize using the Value component, it has no associated InitModal component.

Server

AnalyseHeaders

Import:

import * as analyseHeaders from "@kiwicom/nitro/lib/services/server/analyseHeaders";

Types:

export type CookieSizes = {|
  total: number,
  splitster: number,
  recentSearch: number,
  other: number,
|};

export type Headers = { [string]: string };

export type AnalysePayload = {|
  total: number,
  url: number,
  headers: number,
  cookies: CookieSizes,
  cookiesToRemove: string[],
|};

declare export default (h: Headers, url: string, limit?: number) => AnalysePayload;

CookieSettings

Import:

import * as cookieSettings from "@kiwicom/nitro/lib/services/server/cookieSettings";

Types:

type Cookies = { [key: string]: string };

declare export default (cookies: Cookies) => CookieSettings;

See types:

GetAffiliate

Import:

import * as getAffiliate from "@kiwicom/nitro/lib/services/server/getAffiliate";

Types:

declare export var formatSimple: (entry: string) => string;

type Input = {|
  queryAffilId: ?string, // affilid
  cookiesAffilId: ?string, // AFFILIATE_ID in 'consts/cookies'
|};

declare export default (input: Input) => string | null;

GetBrand

Import:

import * as getBrand from "@kiwicom/nitro/lib/services/server/getBrand";

Types:

type Input = {|
  hostname: string,
  cookieBrand: ?string,
  queryBrand: ?string,
  xForwardedHost: ?string,
|};

declare export default (input: Input) => Brand;

See types:

GetLanguage

Import:

import * as getLanguage from "@kiwicom/nitro/lib/services/server/getLanguage";

Types:

type Input = {|
  path: string,
|};

declare export default (input: Input) => IntlRaw;

See types:

Store

Import:

import * as store from "@kiwicom/nitro/lib/services/server/store";

Types:

export type Data = {|
  airlines: Airlines,
  brandLanguages: BrandLanguages,
  brands: Brands,
  continents: Continents,
  countries: Countries,
  languages: LangInfos,
  intls: IntlsRaw,
  orbits: IntlsRaw,
|};

declare export var data: Data;

export type GetFetchedOptions = {|
  langId: string,
  brandId: string,
|};

declare export var getFetched: (input: GetFetchedOptions) => Fetched;

export type LoadOptions = {|
  dataPath: string,
  modulesPath: string,
|};

declare export var load: (input: LoadOptions) => Promise<void>;

See types:

Store contains all FE’s needed server data. It loads everything for the server’s runtime and has it available in the exported data object.

Be sure to run yarn nitro fetch and yarn nitro translations to have the data ready!

The load function returns a promise, which resolves once all data is loaded and can be accessed by the runtime.

Example:

import { load } from "@kiwicom/nitro/lib/services/server/load";

// ...

load(options).then(() => {
  app.use(/* ...*/);

  app.listen(/* ...*/);
});

Session

Contains everything regarding session data:

Context

Import:

import * as context from "@kiwicom/nitro/lib/services/session/context";

Types:

declare var context: React.Context<Session>;

declare export function useSession(): Session;

export const { Consumer, Provider } = context;

export default context;

See types:

Contains session data. It is static.

Cookies

Import:

import * as cookies from "@kiwicom/nitro/lib/services/session/cookies";

Types:

type Options = {|
  expires?: number | Date,
  domain?: string,
  path?: string,
  secure?: boolean,
|};

declare export var load: (key: Cookie) => ?string;

declare export var save: (key: Cookie, value: string, opts?: Options) => void;

declare export var remove: (key: Cookie, opts?: Options) => void;

See types:

Centralized medium for manipulating cookies.

Ids

Import:

import * as ids from "@kiwicom/nitro/lib/services/session/ids";

Types:

declare export var makeUserId: () => string;

declare export var makeSessionId: () => string;

declare export var makePageViewId: () => string;

Functions for generating IDs.

Init

Import:

import * as init from "@kiwicom/nitro/lib/services/session/init";

Types:

declare export default () => Session;

See types:

Initializes the session context.

Uses the window object, unavailable on the server.

Local

Import:

import * as local from "@kiwicom/nitro/lib/services/session/local";

Types:

declare export var load: (key: Local) => ?string;

declare export var save: (key: Local, value: string) => void;

declare export var remove: (key: Local) => void;

See types:

Centralized medium for manipulating localStorage.

Session

Import:

import * as session from "@kiwicom/nitro/lib/services/session/session";

Types:

declare export var load: (key: Session) => ?string;

declare export var save: (key: Session, value: string) => void;

declare export var remove: (key: Session) => void;

See types:

Centralized medium for manipulating sessionStorage.

Starred

See InitStarred for initializing the service.

Context

Import:

import * as context from "@kiwicom/nitro/lib/services/starred/context";

Types:

export type Context = {|
  list: StarredItem[],
  isMobile: boolean,
  lang: string,
  onAdd: (arg: StarredItem) => void,
  onGoToStarred: (arg: StarredItem) => void,
  onRemove: (id: string, e: SyntheticEvent<HTMLDivElement>) => void,
  onClear: (e: SyntheticEvent<HTMLDivElement>) => void,
  onSetNotice: () => void,
  renderShareDialog: (arg: ShareDialog) => React.Node,
  makeShareUrl: (arg: StarredItem) => string,
|};

declare var context: React.Context<Context>;

declare export function useStarred(): Context;

export const { Consumer, Provider } = context;

See types:

Utils

TODO