import { KintoneRestAPIClient } from '@kintone/rest-api-client'; import i18n from 'i18next'; import { type PluginConfig, type PluginConfigApp, PluginConfigDataSource, type PluginConfigSelf, } from '../common/config'; import { DOCX_CONTENT_TYPE } from '../common/constants'; const checkConfigSelf = (config: PluginConfigSelf, record: kintone.types.SavedFields): string => { const { fieldCode } = config; if (fieldCode === '') { throw new Error(i18n.t('errors.template-field-is-required')); } const field = record[fieldCode]; if (!field) { throw new Error(i18n.t('errors.template-field-is-not-available')); } if (field.type !== 'FILE') { throw new Error(i18n.t('errors.template-field-must-be-an-attachment-field')); } const files = Array.isArray(field.value) ? (field.value as kintone.fieldTypes.File['value']) : []; if (files.length === 0) { throw new Error(i18n.t('errors.template-field-does-not-contain-any-files')); } if (files.length > 1) { throw new Error(i18n.t('errors.template-field-contains-multiple-files')); } if (files[0].contentType !== DOCX_CONTENT_TYPE) { throw new Error(i18n.t('errors.template-file-must-be-a-docx', { contentType: files[0].contentType })); } return files[0].fileKey; }; const checkConfigApp = async (config: PluginConfigApp): Promise => { const { appId, fieldCode, recordId } = config; if (appId === '') { throw new Error(i18n.t('errors.app-id-is-required')); } if (recordId === '') { throw new Error(i18n.t('errors.record-id-is-required')); } if (fieldCode === '') { throw new Error(i18n.t('errors.template-field-is-required')); } const client = new KintoneRestAPIClient(); const { record } = await client.record.getRecord({ app: appId, id: recordId }).catch((_error) => { throw new Error(i18n.t('errors.record-is-not-available')); }); const field = record[fieldCode]; if (!field) { throw new Error(i18n.t('errors.template-field-is-not-available')); } if (field.type !== 'FILE') { throw new Error(i18n.t('errors.template-field-must-be-an-attachment-field')); } const files = Array.isArray(field.value) ? (field.value as kintone.fieldTypes.File['value']) : []; if (files.length === 0) { throw new Error(i18n.t('errors.template-field-does-not-contain-any-files')); } if (files.length > 1) { throw new Error(i18n.t('errors.template-field-contains-multiple-files')); } if (files[0].contentType !== DOCX_CONTENT_TYPE) { throw new Error(i18n.t('errors.template-file-must-be-a-docx', { contentType: files[0].contentType })); } return files[0].fileKey; }; export const checkConfig = async (config: PluginConfig, record: kintone.types.SavedFields): Promise => { if (config.dataSource === PluginConfigDataSource.SELF) { return checkConfigSelf(config, record); } else if (config.dataSource === PluginConfigDataSource.APP) { return checkConfigApp(config); } throw new Error(i18n.t('errors.unexpected-error-occurred')); };