models.js•6.66 kB
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.create = exports.fetch = exports.fetchMany = void 0;
const axios_1 = __importDefault(require("axios"));
const util_1 = require("../util");
const Util = __importStar(require("../util"));
const uuid_1 = require("uuid");
var Endpoint;
(function (Endpoint) {
    Endpoint["FETCH"] = "models/:id";
    Endpoint["FETCH_MANY"] = "models";
    Endpoint["CREATE"] = "models";
})(Endpoint || (Endpoint = {}));
function mapModel(model) {
    const mapped = {
        ...model,
        createdAt: new Date(model.created_at),
        updatedAt: new Date(model.updated_at),
        estimatedCompletedAt: model.estimated_completed_at
            ? new Date(model.estimated_completed_at)
            : undefined,
        thumbnailUrl: model.thumbnail_url ? model.thumbnail_url : undefined,
    };
    delete mapped.created_at;
    delete mapped.updated_at;
    delete mapped.estimated_completed_at;
    delete mapped.thumbnail_url;
    return mapped;
}
/**
 * EverArt List Models (v1/models)
 */
async function fetchMany(...args) {
    const [options] = args;
    const params = [];
    if (options) {
        if (options.beforeId) {
            params.push(`before_id=${encodeURIComponent(options.beforeId)}`);
        }
        if (options.limit) {
            params.push(`limit=${options.limit}`);
        }
        if (options.search) {
            params.push(`search=${encodeURIComponent(options.search)}`);
        }
        if (options.status) {
            params.push(`status=${encodeURIComponent(options.status)}`);
        }
    }
    const endpoint = Endpoint.FETCH_MANY + (params.length > 0 ? `?${params.join('&')}` : '');
    const response = await axios_1.default.get(Util.makeUrl(util_1.APIVersion.V1, endpoint), {
        headers: this.defaultHeaders,
        validateStatus: undefined,
    });
    if (response.status === 200 &&
        Array.isArray(response.data.models) &&
        typeof response.data.has_more === 'boolean') {
        return {
            models: response.data.models.map(mapModel),
            hasMore: response.data.has_more,
        };
    }
    throw new util_1.EverArtError(response.status, 'Failed to get models', response.data);
}
exports.fetchMany = fetchMany;
/**
 * EverArt List Models (v1/models)
 */
async function fetch(...args) {
    const [id] = args;
    const endpoint = Endpoint.FETCH.replace(':id', id);
    const response = await axios_1.default.get(Util.makeUrl(util_1.APIVersion.V1, endpoint), {
        headers: this.defaultHeaders,
        validateStatus: undefined,
    });
    if (response.status === 200 && response.data.model) {
        return mapModel(response.data.model);
    }
    throw new util_1.EverArtError(response.status, 'Failed to fetch model', response.data);
}
exports.fetch = fetch;
/**
 * EverArt List Models (v1/models)
 */
async function create(...args) {
    const [name, subject, images, options] = args;
    // Add input validation
    if (!name || typeof name !== 'string') {
        throw new util_1.EverArtError(400, 'Name is required and must be a string');
    }
    if (!images || !Array.isArray(images) || images.length === 0) {
        throw new util_1.EverArtError(400, 'At least one image is required');
    }
    const imageUrls = images.filter((i) => i.type === 'url').map((i) => i.value);
    const imageUploadTokens = [];
    const files = images.filter((i) => i.type === 'file').map((i) => {
        const name = i.path.split('/').pop() || 'image';
        const contentType = Util.getContentType(name);
        return {
            path: i.path,
            name,
            contentType,
            id: (0, uuid_1.v4)(),
        };
    });
    if (files.length > 0) {
        try {
            const imageUploads = await this.v1.images.uploads(files.map((file) => ({
                filename: file.name,
                content_type: file.contentType,
                id: file.id,
            })));
            await Promise.all(imageUploads.map(async (imageUpload) => {
                const file = files.find((file) => file.id === imageUpload.id);
                if (!file)
                    throw new Error('Could not find associated file for upload');
                try {
                    await Util.uploadFile(file.path, imageUpload.upload_url, file.contentType);
                    imageUploadTokens.push(imageUpload.upload_token);
                }
                catch (error) {
                    throw new util_1.EverArtError(500, `Failed to upload file ${file.name}`, error);
                }
            }));
        }
        catch (error) {
            throw new util_1.EverArtError(500, 'Failed during file upload process', error);
        }
    }
    const body = {
        name,
        subject,
        image_urls: imageUrls,
        image_upload_tokens: imageUploadTokens,
    };
    if (options === null || options === void 0 ? void 0 : options.webhookUrl)
        body.webhook_url = options.webhookUrl;
    const endpoint = Endpoint.CREATE;
    const response = await axios_1.default.post(Util.makeUrl(util_1.APIVersion.V1, endpoint), body, {
        headers: this.defaultHeaders,
        validateStatus: undefined,
    });
    if (response.status === 200 && response.data.model) {
        return mapModel(response.data.model);
    }
    throw new util_1.EverArtError(response.status, 'Failed to create model', response.data);
}
exports.create = create;
//# sourceMappingURL=models.js.map