![require(esm) Backported to Node.js 20, Paving the Way for ESM-Only Packages](https://cdn.sanity.io/images/cgdhsj6q/production/be8ab80c8efa5907bc341c6fefe9aa20d239d890-1600x1097.png?w=400&fit=max&auto=format)
Security News
require(esm) Backported to Node.js 20, Paving the Way for ESM-Only Packages
require(esm) backported to Node.js 20, easing the transition to ESM-only packages and reducing complexity for developers as Node 18 nears end-of-life.
@foxford/foxford-js-sdk
Advanced tools
Набор методом для работы с Фоксфорд
// @flow
import { Foxford } from '@foxford/foxford-js-sdk'
import type { User } from '@foxford/foxford-js-sdk'
const foxSdk = new Foxford()
const getUser = async function () {
const user: User = await foxSdk.user.getUser()
}
Описание интерфейсов можно глянуть в index.d.ts
или index.js.flow
Библиотека сама сходит на скриптом по нужному адресу и вставит его в ваш DOM. После чего проинициализирует виджеты с заданными конфигом. Теперь нет необходимости инициализировать библиотеку виджетов вручную.
Пример инициализации виджетов
const WIDGETS_CONFIG = Object.freeze({
analyticContext: { prefix: 'app', module: '' },
widgets: [
{
name: 'menu',
options: {
header: true,
footer: true,
headerContainer: document.getElementById(HEADER_CONTAINER_NAME),
footerContainer: document.getElementById(FOOTER_CONTAINER_NAME),
},
},
],
})
const sdk = new Foxford()
sdk.widgets.create(WIDGETS_CONFIG)
Саздаем cartItem
и добавляем его в корзину
const sdk = new Foxford()
async function addCourseToCart(id: number) {
try {
const course = await sdk.course.getCourse(id)
// создаем cart-item
const cartItem = sdk.cart.createCartItem(course.id, course.cartItem.type)
// добавляем cart-item в корзину
await sdk.cart.addCartItemToCart(cartItem)
// redirect
} catch (error) {
// error
}
}
Получение информации по курсу
const sdk = new Foxford()
async function getCourse(id: number): Course {
const course = await sdk.course.getCourse(id)
return course
}
Создаем лидреквест и отсылаем его
const sdk = new Foxford()
async function sendLeadRequest({ email, phone, name }) {
const lrData = {
email: email,
phone_number: phone,
name: name,
}
const leadRequest = sdk.leadrequest.createLeadRequest(LEAD_REQUEST_TYPE, 'express.foxford.ru | offer', lrData)
await sdk.leadrequest.send(leadRequest, search)
}
Для отправки юзер эвентов нужно выполнить
const sdk = new Foxford()
async function sendUserEvent(event: 'experiment' | 'funnel' | 'conversion'): void {
await sdk.user.pushEvent(event) // отправка события
}
sendUserEvent('conversion')
В случае крайней необходимости есть возможность делать прямые запросы через настроенный api клиент.
const sdk = new Foxford()
const api = sdk.api
const foxApi = sdk.foxApi
const api = sdk.api
const staticApi = sdk.staticApi
foxApi.post(`/api/${endpoint}`, { data })
// ---------------------------------------------------------------------------------------- //
// Выполняем запрос к внешнему ресурсу
api.get(`https://some.external.source`).then(({ data }) => data)
// ---------------------------------------------------------------------------------------- //
/*
`staticApi` можно использовать для доступа к статичным методам и свойствам апи
* staticApi.create() - для создания нового инстанса
* staticApi.isCancel() - для проверки был ли запрос отменен пользователем
* staticApi.CancelToken - для отмены запросов
*/
// Отмена запроса
const CancelToken = staticApi.CancelToken
const source = CancelToken.source()
staticApi
.get('/user/12345', {
cancelToken: source.token,
})
.catch(function (thrown) {
if (staticApi.isCancel(thrown)) {
console.log('Request canceled', thrown.message)
} else {
// обработка ошибки
}
})
staticApi.post(
'/user/12345',
{
name: 'new name',
},
{
cancelToken: source.token,
}
)
// Отмена запроса (параметр сообщения опциональный)
source.cancel('Operation canceled by the user.')
// Создание инстанса
const customClient = staticApi.create({
baseURL: someCustomURL,
responseType: 'text',
})
Данные плагины могут быть использованы в любой экосистеме(react, vanilla js)
Ознакомьтесь подробнее с документацией по каждому плагину.
FAQs
Foxford sdk for external projects
We found that @foxford/foxford-js-sdk demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
require(esm) backported to Node.js 20, easing the transition to ESM-only packages and reducing complexity for developers as Node 18 nears end-of-life.
Security News
PyPI now supports iOS and Android wheels, making it easier for Python developers to distribute mobile packages.
Security News
Create React App is officially deprecated due to React 19 issues and lack of maintenance—developers should switch to Vite or other modern alternatives.