...

Пример использования сторонней библиотеки

Тема в разделе "Скрипты и разработка", создана пользователем ksannikov, 4 авг 2025.

  1. ksannikov

    ksannikov Активный участник

    Привет!
    Я покажу пример использования сторонних библиотек. на примере библиотеки которая позволяет конвертировать эксель документ в JSON.
    Все подробности в ролике, а ниже код из видео.
    Функция конвертации:

    Код:
    
    import XSLX from "xlsx.full.min.js";

    declare const 
    console: any;
    declare const 
    window: any;

    async function getData(): Promise<void> {
        try {
            if (
    ViewContext.data.file) {
                const 
    xlsRes = await fetch(await ViewContext.data.file.getDownloadUrl());
                const 
    content = await xlsRes.arrayBuffer();

                const 
    book = XSLX.read(content, { type: "array" });

                
    let rowObj = XSLX.utils.sheet_to_row_object_array(book.Sheets[book.SheetNames[0]]);

                
    Context.data.product_data = JSON.stringify(rowObj);
            }

        } catch (
    e) {
            throw new 
    Error(`Ошибка чтения EXCEL файла: ${e.message}`)
        }
    }
    Функция для создания элементов приложений:

    Код:
    
    async function createProducts(): Promise<void> {
        if (!
    Context.data.product_data) return
        const 
    products = JSON.parse(Context.data.product_data) as any[]
        
    let all_brands = await Namespace.app.brand.search().where(f => f.__deletedAt.eq(null)).size(100).all();
        
    let new_brands: typeof all_brands = []
        
    let all_categories = await Namespace.app.category.search().where(f => f.__deletedAt.eq(null)).size(100).all();
        
    let new_categories: typeof all_categories = []
        
    let new_products: BaseApplicationItem<any, any>[] = []
        for (
    let item of products) {
            
    let brand: any
            let category
    : any

            
    if (item['Бренд']) {
                
    brand = all_brands.find(f => f.data.__name == item['Бренд']);
                if (!
    brand) brand = new_brands.find(f => f.data.__name == item['Бренд']);
                if (!
    brand) {
                    const 
    new_brand = Namespace.app.brand.create();
                    
    new_brand.data.__name = item['Бренд']
                    
    new_brands.push(new_brand)
                    
    brand = new_brand
                
    }
            }

            if (
    item['Категория продукта']) {
                
    category = all_categories.find(f => f.data.__name == item['Категория продукта']);
                if (!
    category) category = new_categories.find(f => f.data.__name == item['Категория продукта']);
                if (!
    category) {
                    const 
    new_category = Namespace.app.category.create();
                    
    new_category.data.__name = item['Категория продукта']
                    
    new_categories.push(new_category)
                    
    category = new_category
                
    }
            }

            
    let product = Application.create();
            
    product.data.__name = item['Название']
            
    product.data.brand = brand
            product
    .data.category = category
            product
    .data.amount = item['Количество']
            
    product.data.description = item['Описание']
            
    new_products.push(product)
        }

        if (
    new_brands?.length) await Namespace.app.brand.batch().save().items(new_brands).all()
        if (
    new_categories?.length) await Namespace.app.category.batch().save().items(new_categories).all()
        if (
    new_products?.length) await Namespace.app.product_catalog.batch().save().items(new_products).all()
    }
    Еще больше полезной информации в ТГ канале WhatDaELMA365