...

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

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

  1. ksannikov

    ksannikov Участник

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

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

    declare const 
    consoleany;
    declare const 
    windowany;

    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.__deletedAt.eq(null)).size(100).all();
        
    let new_brandstypeof all_brands = []
        
    let all_categories await Namespace.app.category.search().where(=> f.__deletedAt.eq(null)).size(100).all();
        
    let new_categoriestypeof all_categories = []
        
    let new_productsBaseApplicationItem<anyany>[] = []
        for (
    let item of products) {
            
    let brandany
            let category
    any

            
    if (item['Бренд']) {
                
    brand all_brands.find(=> f.data.__name == item['Бренд']);
                if (!
    brandbrand new_brands.find(=> 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.data.__name == item['Категория продукта']);
                if (!
    categorycategory new_categories.find(=> 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?.lengthawait Namespace.app.brand.batch().save().items(new_brands).all()
        if (
    new_categories?.lengthawait Namespace.app.category.batch().save().items(new_categories).all()
        if (
    new_products?.lengthawait Namespace.app.product_catalog.batch().save().items(new_products).all()
    }
    Еще больше полезной информации в ТГ канале WhatDaELMA365