How to use @vtex/api - 10 common examples

To help you get started, we’ve selected a few @vtex/api examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github vtex / toolbelt / src / modules / workspace / abtest / utils.ts View on Github external
id: '',
    params: {},
  },
  userAgent,
  workspace: 'master',
  requestId: '',
  operationId: '',
  logger: dummyLogger,
  platform: '',
}

const options = { timeout: (envTimeout || DEFAULT_TIMEOUT) as number }

// Clients for the 'master' workspace
export const abtester = new ABTester(contextForMaster, { ...options, retries: 3 })
export const apps = new Apps(contextForMaster, options)

export const formatDays = (days: number) => {
  let suffix = 'days'
  if (days === 1) {
    suffix = 'day'
  }
  return `${numbro(days).format('0,0')} ${suffix}`
}

export const formatDuration = (durationInMinutes: number) => {
  const minutes = durationInMinutes % 60
  const hours = Math.trunc(durationInMinutes / 60) % 24
  const days = Math.trunc(durationInMinutes / (60 * 24))
  return `${days} days, ${hours} hours and ${minutes} minutes`
}
github vtex-apps / store-graphql / node / index.ts View on Github external
import { LRUCache, Service } from '@vtex/api'

import { Clients } from './clients'
import { dataSources } from './dataSources'
import { schemaDirectives } from './directives'
import { resolvers } from './resolvers'

const TWO_SECONDS_MS = 2 * 1000
const THREE_SECONDS_MS = 3 * 1000
const SIX_SECONDS_MS = 6 * 1000
const TEN_SECONDS_MS = 10 * 1000
const THIRTY_SECONDS_MS = 30 * 1000

// Segments are small and immutable.
const MAX_SEGMENT_CACHE = 10000
const segmentCache = new LRUCache({ max: MAX_SEGMENT_CACHE })
const catalogCache = new LRUCache({max: 3000})
const messagesCache = new LRUCache({max: 3000})

metrics.trackCache('segment', segmentCache)
metrics.trackCache('catalog', catalogCache)
metrics.trackCache('messages', messagesCache)

export default new Service({
  clients: {
    implementation: Clients,
    options: {
      checkout: {
        concurrency: 10,
        timeout: THIRTY_SECONDS_MS,
      },
      default: {
github vtex-apps / store-graphql / node / index.ts View on Github external
import { Clients } from './clients'
import { dataSources } from './dataSources'
import { schemaDirectives } from './directives'
import { resolvers } from './resolvers'

const TWO_SECONDS_MS = 2 * 1000
const THREE_SECONDS_MS = 3 * 1000
const SIX_SECONDS_MS = 6 * 1000
const TEN_SECONDS_MS = 10 * 1000
const THIRTY_SECONDS_MS = 30 * 1000

// Segments are small and immutable.
const MAX_SEGMENT_CACHE = 10000
const segmentCache = new LRUCache({ max: MAX_SEGMENT_CACHE })
const catalogCache = new LRUCache({max: 3000})
const messagesCache = new LRUCache({max: 3000})

metrics.trackCache('segment', segmentCache)
metrics.trackCache('catalog', catalogCache)
metrics.trackCache('messages', messagesCache)

export default new Service({
  clients: {
    implementation: Clients,
    options: {
      checkout: {
        concurrency: 10,
        timeout: THIRTY_SECONDS_MS,
      },
      default: {
        retries: 2,
        timeout: THREE_SECONDS_MS,
github vtex-apps / store-graphql / node / index.ts View on Github external
import { Clients } from './clients'
import { dataSources } from './dataSources'
import { schemaDirectives } from './directives'
import { resolvers } from './resolvers'

const TWO_SECONDS_MS = 2 * 1000
const THREE_SECONDS_MS = 3 * 1000
const SIX_SECONDS_MS = 6 * 1000
const TEN_SECONDS_MS = 10 * 1000
const THIRTY_SECONDS_MS = 30 * 1000

// Segments are small and immutable.
const MAX_SEGMENT_CACHE = 10000
const segmentCache = new LRUCache({ max: MAX_SEGMENT_CACHE })
const catalogCache = new LRUCache({max: 3000})
const messagesCache = new LRUCache({max: 3000})

metrics.trackCache('segment', segmentCache)
metrics.trackCache('catalog', catalogCache)
metrics.trackCache('messages', messagesCache)

export default new Service({
  clients: {
    implementation: Clients,
    options: {
      checkout: {
        concurrency: 10,
        timeout: THIRTY_SECONDS_MS,
      },
      default: {
        retries: 2,
github vtex / toolbelt / scripts / mass-apps-operations.ts View on Github external
const main = async () => {
  try {
    console.log('\n' + dragons)
    if (!await confirm(accounts.length, command, app)) {
      console.log('What do we say to the God of Death? Not today.')
      process.exit(2)
    }
    console.log(c.blue('I sure hope you know what you\'re doing.'))

    const workspace = `${WORKSPACE_NAME_PREFIX}-${command}`
    const workspaces = new Workspaces({
      account: 'vtex',
      workspace: 'master',
      authToken,
      userAgent: USER_AGENT,
      region: REGION,
    })

    await Promise.map(accounts, queue.wrap(uninstall(workspace, workspaces)))

    if (skippedAccounts.length === 0) {
      console.log('✅  All done!')
    } else {
      writeJSON('./errors.json', errorLogs, {spaces: 2})
      writeJSON('./skipped-accounts.json', skippedAccounts.map(a => ({name: a})), {spaces: 2})
      console.log()
      console.log('🚫  The following accounts were skipped:')
github vtex / toolbelt / scripts / mass-apps-operations.ts View on Github external
const uninstall = (workspace: string, workspaces: Workspaces) => async ({name: account}: {name: string}) => {
  const apps = new Apps({
    account,
    workspace,
    authToken,
    userAgent: USER_AGENT,
    region: REGION,
  })
  const prefix = c.bold(`[${account}/${workspace}]`)
  const log = (s) => console.log(`${prefix} ${s}`)

  log('Creating workspace...')
  try {
    await workspaces.create(account, workspace)
  } catch (e) {
    const code = e.response.data.code
    if (code === 'WorkspaceAlreadyExists') {
      try {
github vtex-apps / store-graphql / node / globals.ts View on Github external
import {
  IOContext,
  MetricsAccumulator,
  SegmentData,
  ServiceContext,
} from '@vtex/api'

import { Clients } from './clients'
import { IdentityDataSource } from './dataSources/identity'

if (!global.metrics) {
  console.error('No global.metrics at require time')
  global.metrics = new MetricsAccumulator()
}

declare global {
  type Context = ServiceContext

  interface CustomContext {
    cookie: string
    dataSources: StoreGraphQLDataSources
    originalPath: string
    vtex: CustomIOContext
  }

  interface CustomIOContext extends IOContext {
    currentProfile: CurrentProfile
    segment?: SegmentData
    orderFormId?: string
github vtex-apps / store-graphql / node / resolvers / list / util.ts View on Github external
const checkListItemQuantity = (quantity: any) => {
  if (!quantity || quantity < 0) {
    throw new UserInputError('The item quantity should be greater than 0')
  }
}
github vtex-apps / store-graphql / node / resolvers / catalog / index.ts View on Github external
facets: async (
    _: any,
    { facets, query, map, hideUnavailableItems }: FacetsArgs,
    ctx: Context
  ) => {
    const {
      clients: { catalog },
      clients,
    } = ctx

    if (facets && facets.includes('undefined')) {
      throw new UserInputError('Bad facets parameter provided')
    }

    let result
    const translatedQuery = await translateToStoreDefaultLanguage(
      clients,
      query
    )
    const segmentData = ctx.vtex.segment
    const salesChannel = (segmentData && segmentData.channel.toString()) || ''

    const unavailableString = hideUnavailableItems
      ? `&fq=isAvailablePerSalesChannel_${salesChannel}:1`
      : ''
    if (facets) {
      result = await catalog.facets(facets)
    } else {
github vtex-apps / store-graphql / node / clients / utils.ts View on Github external
export function statusToError(e: any) {
  if (!e.response) {
    throw e
  }

  const { response } = e as AxiosError
  const { status } = response!

  if (status === 401) {
    throw new AuthenticationError(e)
  }
  if (status === 403) {
    throw new ForbiddenError(e)
  }
  if (status === 400) {
    throw new UserInputError(e)
  }

  throw e
}