update
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
# MONOCOOP
|
||||
|
||||
Моно-репозиторий компонент Цифрового Кооператива.
|
||||
Моно-репозиторий компонент клиента системы электронного документооборота для потребительских и производственных кооперативов.
|
||||
|
||||
## Инициализация
|
||||
```
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
{
|
||||
"lastMigration": "009_edit_draft_1.ts"
|
||||
"local": "010_edit_all_drafts.ts",
|
||||
"test": "010_edit_all_drafts.ts"
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import {Migration} from '../src/migration_interface'
|
||||
import { api } from '../src/eos'
|
||||
import { Cooperative, DraftContract, SovietContract } from 'cooptypes';
|
||||
import { Registry } from 'coopdoc-generator-ts';
|
||||
|
||||
export class InitialMigration implements Migration {
|
||||
async run(): Promise<void> {
|
||||
|
||||
const editTranslation = async(params: DraftContract.Actions.EditTranslation.IEditTranslation) => {
|
||||
await api.transact({
|
||||
actions: [
|
||||
{
|
||||
account: DraftContract.contractName.production,
|
||||
name: DraftContract.Actions.EditTranslation.actionName,
|
||||
authorization: [
|
||||
{
|
||||
actor: 'eosio',
|
||||
permission: "active",
|
||||
},
|
||||
],
|
||||
data: {
|
||||
...params,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
blocksBehind: 3,
|
||||
expireSeconds: 30,
|
||||
}
|
||||
)
|
||||
|
||||
console.log("Перевод установлен для:", params.translate_id)
|
||||
}
|
||||
|
||||
const editDraft = async(params: DraftContract.Actions.EditDraft.IEditDraft) => {
|
||||
|
||||
await api.transact(
|
||||
{
|
||||
actions: [
|
||||
{
|
||||
account: DraftContract.contractName.production,
|
||||
name: DraftContract.Actions.EditDraft.actionName,
|
||||
authorization: [
|
||||
{
|
||||
actor: 'eosio',
|
||||
permission: "active",
|
||||
},
|
||||
],
|
||||
data: {
|
||||
...params,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
blocksBehind: 3,
|
||||
expireSeconds: 30,
|
||||
}
|
||||
)
|
||||
|
||||
console.log("Шаблон отредактирован: ", params.title, params.registry_id)
|
||||
}
|
||||
|
||||
try {
|
||||
const drafts = await api.rpc.get_table_rows({json: true, code: 'draft', scope: 'draft', table: 'drafts'})
|
||||
// console.log(drafts)
|
||||
|
||||
for (const draft of drafts.rows) {
|
||||
const template = Registry[(draft.registry_id as unknown) as keyof typeof Registry]
|
||||
|
||||
await editDraft({
|
||||
scope: DraftContract.contractName.production,
|
||||
username: 'eosio',
|
||||
registry_id: draft.registry_id,
|
||||
title: template.Template.title,
|
||||
description: template.Template.description,
|
||||
context: template.Template.context,
|
||||
model: JSON.stringify(template.Template.model),
|
||||
})
|
||||
|
||||
await editTranslation({
|
||||
scope: DraftContract.contractName.production,
|
||||
username: 'eosio',
|
||||
translate_id: draft.default_translation_id,
|
||||
data: JSON.stringify(template.Template.translations.ru)
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
console.log('update drafts successful');
|
||||
} catch (error) {
|
||||
console.error('Error during migration:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
import {Migration} from '../src/migration_interface'
|
||||
import { api } from '../src/eos'
|
||||
import {Migration} from '../../src/migration_interface'
|
||||
import { api } from '../../src/eos'
|
||||
import { Cooperative, DraftContract, SovietContract } from 'cooptypes';
|
||||
import { Registry } from 'coopdoc-generator-ts';
|
||||
|
||||
@@ -4,27 +4,35 @@ import { getDirname } from './utils/dirname';
|
||||
import { MigrationFactory } from './factory';
|
||||
|
||||
interface MigrationState {
|
||||
lastMigration: string | null;
|
||||
[env: string]: string | null;
|
||||
}
|
||||
|
||||
export class Migrator {
|
||||
private stateFilePath: string;
|
||||
private state: MigrationState;
|
||||
private env: string;
|
||||
|
||||
constructor() {
|
||||
const __dirname = getDirname(import.meta.url);
|
||||
this.stateFilePath = path.join(__dirname, '../migration_state.json');
|
||||
this.state = { lastMigration: null };
|
||||
this.env = process.env.NODE_ENV || 'local'; // Получаем текущее окружение
|
||||
this.state = { [this.env]: null }; // Инициализируем состояние для текущего окружения
|
||||
}
|
||||
|
||||
// Загружаем состояние из файла
|
||||
private async loadState(): Promise<void> {
|
||||
try {
|
||||
if (await fs.pathExists(this.stateFilePath)) {
|
||||
const stateData = await fs.readFile(this.stateFilePath, 'utf-8'); // Используем fs напрямую
|
||||
const stateData = await fs.readFile(this.stateFilePath, 'utf-8');
|
||||
this.state = JSON.parse(stateData);
|
||||
} else {
|
||||
// Если файл не существует, создаем его с начальным значением
|
||||
// Если файл не существует, создаем его с начальными значениями для всех окружений
|
||||
await this.saveState();
|
||||
}
|
||||
|
||||
// Если состояние для текущего окружения отсутствует, инициализируем его
|
||||
if (!this.state[this.env]) {
|
||||
this.state[this.env] = null;
|
||||
await this.saveState();
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -35,29 +43,28 @@ export class Migrator {
|
||||
// Сохраняем состояние в файл
|
||||
private async saveState(): Promise<void> {
|
||||
try {
|
||||
await fs.writeFile(this.stateFilePath, JSON.stringify(this.state, null, 2)); // Используем fs напрямую
|
||||
await fs.writeFile(this.stateFilePath, JSON.stringify(this.state, null, 2));
|
||||
} catch (error) {
|
||||
console.error('Failed to save migration state:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Получаем список миграций, начиная с последней выполненной, и исключаем ненужные файлы
|
||||
// Получаем список миграций, начиная с последней выполненной для текущего окружения
|
||||
private async getPendingMigrations(): Promise<string[]> {
|
||||
const __dirname = getDirname(import.meta.url);
|
||||
const migrationsDir = path.join(__dirname, '../migrations');
|
||||
const allMigrationFiles = await fs.readdir(migrationsDir); // Используем fs напрямую
|
||||
const allMigrationFiles = await fs.readdir(migrationsDir);
|
||||
|
||||
// Фильтруем файлы, чтобы использовать только те, что соответствуют шаблону миграций (например, '001_some_migration.ts')
|
||||
const migrationFiles = allMigrationFiles.filter(file => file.match(/^\d+.*\.ts$/));
|
||||
|
||||
if (this.state.lastMigration) {
|
||||
const lastMigrationIndex = migrationFiles.indexOf(this.state.lastMigration);
|
||||
if (this.state[this.env]) {
|
||||
const lastMigrationIndex = migrationFiles.indexOf(this.state[this.env] as string);
|
||||
return lastMigrationIndex >= 0
|
||||
? migrationFiles.slice(lastMigrationIndex + 1) // Возвращаем миграции после последней выполненной
|
||||
: migrationFiles; // Если последняя миграция не найдена (возможно, была удалена), выполняем все
|
||||
? migrationFiles.slice(lastMigrationIndex + 1)
|
||||
: migrationFiles; // Если последняя миграция не найдена, выполняем все миграции
|
||||
}
|
||||
|
||||
return migrationFiles; // Если миграции еще не запускались, выполняем все
|
||||
return migrationFiles; // Если миграции еще не запускались для текущего окружения, выполняем все
|
||||
}
|
||||
|
||||
// Основной метод для выполнения миграций
|
||||
@@ -78,8 +85,8 @@ export class Migrator {
|
||||
console.log(`Running migration: ${file}`);
|
||||
await migration.run();
|
||||
|
||||
// Обновляем состояние и сохраняем его
|
||||
this.state.lastMigration = file;
|
||||
// Обновляем состояние для текущего окружения и сохраняем его
|
||||
this.state[this.env] = file;
|
||||
await this.saveState();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user