@roit/roit-data-firestore 1.2.43 → 1.2.45
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/archive/ArchivePluginRegistry.d.ts +78 -0
- package/dist/archive/ArchivePluginRegistry.js +135 -0
- package/dist/archive/ArchiveService.d.ts +61 -11
- package/dist/archive/ArchiveService.js +138 -120
- package/dist/archive/IArchivePlugin.d.ts +102 -0
- package/dist/archive/IArchivePlugin.js +12 -0
- package/dist/archive/index.d.ts +2 -0
- package/dist/archive/index.js +11 -0
- package/dist/cache/CacheResolver.js +6 -5
- package/dist/config/ArchiveConfig.d.ts +17 -12
- package/dist/config/ArchiveConfig.js +25 -41
- package/dist/config/BaseRepository.js +1 -1
- package/dist/config/ReadonlyRepository.js +1 -1
- package/dist/exception/RepositoryException.js +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +10 -1
- package/dist/model/CacheProviders.d.ts +1 -2
- package/dist/model/CacheProviders.js +1 -2
- package/dist/query/ManualQueryHelper.js +0 -1
- package/dist/query/QueryPredicateFunctionTransform.js +4 -1
- package/dist/template/FunctionAggregationTemplate.txt +1 -1
- package/dist/template/FunctionAverageTemplate.txt +1 -1
- package/dist/template/FunctionCountTemplate.txt +20 -25
- package/dist/template/FunctionCreateOrUpdateTemplate.txt +69 -20
- package/dist/template/FunctionCreateTemplate.txt +15 -13
- package/dist/template/FunctionDeleteTemplate.txt +45 -13
- package/dist/template/FunctionFindAllTemplate.txt +39 -23
- package/dist/template/FunctionFindByIdTemplate.txt +24 -14
- package/dist/template/FunctionQueryTemplate.txt +67 -41
- package/dist/template/FunctionSumTemplate.txt +48 -32
- package/dist/template/FunctionUpdatePartialTemplate.txt +76 -21
- package/dist/template/FunctionUpdateTemplate.txt +64 -17
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/dist/cache/providers/RedisCacheArchiveProvider.d.ts +0 -19
- package/dist/cache/providers/RedisCacheArchiveProvider.js +0 -115
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { IArchivePlugin } from './IArchivePlugin';
|
|
2
|
+
/**
|
|
3
|
+
* Registry para o plugin de arquivamento
|
|
4
|
+
*
|
|
5
|
+
* Permite que aplicações registrem um plugin de archive (como firestore-archive)
|
|
6
|
+
* para habilitar funcionalidades de arquivamento de documentos.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* import { registerArchivePlugin, getArchivePlugin } from '@roit/roit-data-firestore';
|
|
11
|
+
* import { createArchivePlugin } from 'firestore-archive';
|
|
12
|
+
*
|
|
13
|
+
* // No início da aplicação
|
|
14
|
+
* registerArchivePlugin(createArchivePlugin());
|
|
15
|
+
*
|
|
16
|
+
* // Em qualquer lugar da aplicação
|
|
17
|
+
* const plugin = getArchivePlugin();
|
|
18
|
+
* if (plugin.isEnabled()) {
|
|
19
|
+
* const data = await plugin.getArchivedDocument({
|
|
20
|
+
* collection: 'orders',
|
|
21
|
+
* docId: 'abc123',
|
|
22
|
+
* archivePath: 'gs://bucket/project/orders/YYYY/MM/DD/{ts}_abc123.json.gz',
|
|
23
|
+
* });
|
|
24
|
+
* }
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
declare class ArchivePluginRegistry {
|
|
28
|
+
private static instance;
|
|
29
|
+
private plugin;
|
|
30
|
+
private constructor();
|
|
31
|
+
static getInstance(): ArchivePluginRegistry;
|
|
32
|
+
/**
|
|
33
|
+
* Registra um plugin de archive
|
|
34
|
+
*/
|
|
35
|
+
register(plugin: IArchivePlugin): void;
|
|
36
|
+
/**
|
|
37
|
+
* Retorna o plugin registrado (ou NoOp se nenhum foi registrado)
|
|
38
|
+
*/
|
|
39
|
+
getPlugin(): IArchivePlugin;
|
|
40
|
+
/**
|
|
41
|
+
* Verifica se um plugin real foi registrado
|
|
42
|
+
*/
|
|
43
|
+
hasPlugin(): boolean;
|
|
44
|
+
/**
|
|
45
|
+
* Reseta o registry (útil para testes)
|
|
46
|
+
*/
|
|
47
|
+
reset(): void;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Registra um plugin de archive
|
|
51
|
+
* Deve ser chamado no início da aplicação, antes de usar repositórios
|
|
52
|
+
*
|
|
53
|
+
* @param plugin - Instância do plugin de archive
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* ```typescript
|
|
57
|
+
* import { registerArchivePlugin } from '@roit/roit-data-firestore';
|
|
58
|
+
* import { createArchivePlugin } from 'firestore-archive';
|
|
59
|
+
*
|
|
60
|
+
* // No bootstrap da aplicação
|
|
61
|
+
* registerArchivePlugin(createArchivePlugin());
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
export declare function registerArchivePlugin(plugin: IArchivePlugin): void;
|
|
65
|
+
/**
|
|
66
|
+
* Retorna o plugin de archive registrado
|
|
67
|
+
* Se nenhum plugin foi registrado, retorna um plugin NoOp que desabilita todas as operações
|
|
68
|
+
*/
|
|
69
|
+
export declare function getArchivePlugin(): IArchivePlugin;
|
|
70
|
+
/**
|
|
71
|
+
* Verifica se um plugin de archive foi registrado
|
|
72
|
+
*/
|
|
73
|
+
export declare function hasArchivePlugin(): boolean;
|
|
74
|
+
/**
|
|
75
|
+
* Reseta o registry de plugins (útil para testes)
|
|
76
|
+
*/
|
|
77
|
+
export declare function resetArchivePlugin(): void;
|
|
78
|
+
export { ArchivePluginRegistry };
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ArchivePluginRegistry = exports.resetArchivePlugin = exports.hasArchivePlugin = exports.getArchivePlugin = exports.registerArchivePlugin = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Plugin NoOp - usado quando nenhum plugin de archive foi registrado
|
|
6
|
+
* Todas as operações retornam valores padrão indicando que archive está desabilitado
|
|
7
|
+
*/
|
|
8
|
+
class NoOpArchivePlugin {
|
|
9
|
+
isEnabled() {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
isDocumentArchived(_doc) {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
async getArchivedDocument(_params) {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
async updateArchivedDocument(_params) {
|
|
19
|
+
return {
|
|
20
|
+
result: { success: false, message: 'Archive plugin not registered' },
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
async deleteArchivedDocument(_params) {
|
|
24
|
+
return { success: false, message: 'Archive plugin not registered' };
|
|
25
|
+
}
|
|
26
|
+
async invalidateCache(_collection, _docId) {
|
|
27
|
+
// No-op
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Registry para o plugin de arquivamento
|
|
32
|
+
*
|
|
33
|
+
* Permite que aplicações registrem um plugin de archive (como firestore-archive)
|
|
34
|
+
* para habilitar funcionalidades de arquivamento de documentos.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```typescript
|
|
38
|
+
* import { registerArchivePlugin, getArchivePlugin } from '@roit/roit-data-firestore';
|
|
39
|
+
* import { createArchivePlugin } from 'firestore-archive';
|
|
40
|
+
*
|
|
41
|
+
* // No início da aplicação
|
|
42
|
+
* registerArchivePlugin(createArchivePlugin());
|
|
43
|
+
*
|
|
44
|
+
* // Em qualquer lugar da aplicação
|
|
45
|
+
* const plugin = getArchivePlugin();
|
|
46
|
+
* if (plugin.isEnabled()) {
|
|
47
|
+
* const data = await plugin.getArchivedDocument({
|
|
48
|
+
* collection: 'orders',
|
|
49
|
+
* docId: 'abc123',
|
|
50
|
+
* archivePath: 'gs://bucket/project/orders/YYYY/MM/DD/{ts}_abc123.json.gz',
|
|
51
|
+
* });
|
|
52
|
+
* }
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
class ArchivePluginRegistry {
|
|
56
|
+
constructor() {
|
|
57
|
+
// Inicializa com NoOp por padrão
|
|
58
|
+
this.plugin = new NoOpArchivePlugin();
|
|
59
|
+
}
|
|
60
|
+
static getInstance() {
|
|
61
|
+
if (!ArchivePluginRegistry.instance) {
|
|
62
|
+
ArchivePluginRegistry.instance = new ArchivePluginRegistry();
|
|
63
|
+
}
|
|
64
|
+
return ArchivePluginRegistry.instance;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Registra um plugin de archive
|
|
68
|
+
*/
|
|
69
|
+
register(plugin) {
|
|
70
|
+
this.plugin = plugin;
|
|
71
|
+
console.log('[ArchivePluginRegistry] Archive plugin registered successfully');
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Retorna o plugin registrado (ou NoOp se nenhum foi registrado)
|
|
75
|
+
*/
|
|
76
|
+
getPlugin() {
|
|
77
|
+
return this.plugin;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Verifica se um plugin real foi registrado
|
|
81
|
+
*/
|
|
82
|
+
hasPlugin() {
|
|
83
|
+
return !(this.plugin instanceof NoOpArchivePlugin);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Reseta o registry (útil para testes)
|
|
87
|
+
*/
|
|
88
|
+
reset() {
|
|
89
|
+
this.plugin = new NoOpArchivePlugin();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
exports.ArchivePluginRegistry = ArchivePluginRegistry;
|
|
93
|
+
ArchivePluginRegistry.instance = null;
|
|
94
|
+
// ========== Funções de conveniência ==========
|
|
95
|
+
/**
|
|
96
|
+
* Registra um plugin de archive
|
|
97
|
+
* Deve ser chamado no início da aplicação, antes de usar repositórios
|
|
98
|
+
*
|
|
99
|
+
* @param plugin - Instância do plugin de archive
|
|
100
|
+
*
|
|
101
|
+
* @example
|
|
102
|
+
* ```typescript
|
|
103
|
+
* import { registerArchivePlugin } from '@roit/roit-data-firestore';
|
|
104
|
+
* import { createArchivePlugin } from 'firestore-archive';
|
|
105
|
+
*
|
|
106
|
+
* // No bootstrap da aplicação
|
|
107
|
+
* registerArchivePlugin(createArchivePlugin());
|
|
108
|
+
* ```
|
|
109
|
+
*/
|
|
110
|
+
function registerArchivePlugin(plugin) {
|
|
111
|
+
ArchivePluginRegistry.getInstance().register(plugin);
|
|
112
|
+
}
|
|
113
|
+
exports.registerArchivePlugin = registerArchivePlugin;
|
|
114
|
+
/**
|
|
115
|
+
* Retorna o plugin de archive registrado
|
|
116
|
+
* Se nenhum plugin foi registrado, retorna um plugin NoOp que desabilita todas as operações
|
|
117
|
+
*/
|
|
118
|
+
function getArchivePlugin() {
|
|
119
|
+
return ArchivePluginRegistry.getInstance().getPlugin();
|
|
120
|
+
}
|
|
121
|
+
exports.getArchivePlugin = getArchivePlugin;
|
|
122
|
+
/**
|
|
123
|
+
* Verifica se um plugin de archive foi registrado
|
|
124
|
+
*/
|
|
125
|
+
function hasArchivePlugin() {
|
|
126
|
+
return ArchivePluginRegistry.getInstance().hasPlugin();
|
|
127
|
+
}
|
|
128
|
+
exports.hasArchivePlugin = hasArchivePlugin;
|
|
129
|
+
/**
|
|
130
|
+
* Reseta o registry de plugins (útil para testes)
|
|
131
|
+
*/
|
|
132
|
+
function resetArchivePlugin() {
|
|
133
|
+
ArchivePluginRegistry.getInstance().reset();
|
|
134
|
+
}
|
|
135
|
+
exports.resetArchivePlugin = resetArchivePlugin;
|
|
@@ -1,40 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Interface para opções de atualização de documento arquivado
|
|
3
|
+
*/
|
|
4
|
+
interface UpdateArchivedDocumentOptions {
|
|
5
|
+
/** Se true, remove o documento arquivado após a atualização (desarquivamento) */
|
|
6
|
+
unarchive?: boolean;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Resultado de operações de arquivamento
|
|
10
|
+
*/
|
|
11
|
+
interface ArchiveOperationResult {
|
|
12
|
+
success: boolean;
|
|
13
|
+
message?: string;
|
|
14
|
+
error?: Error;
|
|
15
|
+
}
|
|
1
16
|
export declare class ArchiveService {
|
|
2
17
|
private static instance;
|
|
3
18
|
private static readonly lock;
|
|
4
19
|
private static isInitializing;
|
|
5
|
-
private storage;
|
|
6
|
-
private bucketName;
|
|
7
20
|
private config;
|
|
8
|
-
|
|
21
|
+
/** ProjectId do Firestore sendo arquivado (para organização de paths) */
|
|
9
22
|
private projectId;
|
|
10
|
-
private firestore;
|
|
11
23
|
private isInitialized;
|
|
24
|
+
private logger;
|
|
12
25
|
/**
|
|
13
|
-
|
|
14
|
-
|
|
26
|
+
* Construtor privado para prevenir instanciação direta
|
|
27
|
+
*/
|
|
15
28
|
private constructor();
|
|
16
29
|
static getInstance(): Promise<ArchiveService>;
|
|
17
30
|
private initialize;
|
|
18
31
|
static resetInstance(): void;
|
|
19
32
|
/**
|
|
20
33
|
* Verifica se o arquivamento está habilitado
|
|
34
|
+
* Requer que o plugin firestore-archive esteja registrado
|
|
21
35
|
*/
|
|
22
36
|
isEnabled(): boolean;
|
|
23
37
|
/**
|
|
24
38
|
* Verifica se um documento está arquivado
|
|
25
39
|
*/
|
|
26
40
|
isDocumentArchived(documentData: any): boolean;
|
|
27
|
-
private pipeline;
|
|
28
|
-
/**
|
|
29
|
-
* Recupera documento arquivado em formato JSON
|
|
30
|
-
*/
|
|
31
|
-
private retrieveJsonDocument;
|
|
32
41
|
/**
|
|
33
42
|
* Verifica se um documento está arquivado e recupera seus dados completos
|
|
34
43
|
*/
|
|
35
44
|
getArchivedDocument(collectionName: string, doc: any): Promise<Record<string, any> | null>;
|
|
45
|
+
/**
|
|
46
|
+
* Atualiza um documento arquivado no Cloud Storage
|
|
47
|
+
* Usado quando um documento arquivado é atualizado no Firestore
|
|
48
|
+
*
|
|
49
|
+
* @param collectionName - Nome da collection
|
|
50
|
+
* @param docId - ID do documento
|
|
51
|
+
* @param newData - Novos dados a serem mesclados com o documento arquivado
|
|
52
|
+
* @param archivePath - Path completo do objeto no Storage, normalmente o `fbArchivePath` do stub.
|
|
53
|
+
* @param options - Opções de atualização
|
|
54
|
+
* @returns Resultado da operação e dados mesclados
|
|
55
|
+
*/
|
|
56
|
+
updateArchivedDocument(collectionName: string, docId: string, newData: Record<string, any>, archivePath: string, options?: UpdateArchivedDocumentOptions): Promise<{
|
|
57
|
+
result: ArchiveOperationResult;
|
|
58
|
+
mergedData?: Record<string, any>;
|
|
59
|
+
}>;
|
|
60
|
+
/**
|
|
61
|
+
* Deleta um documento arquivado do Cloud Storage
|
|
62
|
+
* Usado quando um documento é permanentemente deletado ou restaurado
|
|
63
|
+
*
|
|
64
|
+
* @param collectionName - Nome da collection
|
|
65
|
+
* @param docId - ID do documento
|
|
66
|
+
* @param archivePath - Path completo do objeto no Storage, normalmente o `fbArchivePath` do stub.
|
|
67
|
+
* @returns Resultado da operação
|
|
68
|
+
*/
|
|
69
|
+
deleteArchivedDocument(collectionName: string, docId: string, archivePath: string): Promise<ArchiveOperationResult>;
|
|
70
|
+
/**
|
|
71
|
+
* Recupera dados completos de um documento arquivado e o prepara para restauração
|
|
72
|
+
* Combina os dados do stub (Firestore) com os dados arquivados (Storage)
|
|
73
|
+
*
|
|
74
|
+
* @param collectionName - Nome da collection
|
|
75
|
+
* @param stubData - Dados do stub no Firestore (inclui fbArchivedAt)
|
|
76
|
+
* @returns Dados completos mesclados ou null se não encontrado
|
|
77
|
+
*/
|
|
78
|
+
getCompleteArchivedDocument(collectionName: string, stubData: Record<string, any>): Promise<Record<string, any> | null>;
|
|
36
79
|
/**
|
|
37
80
|
* Limpa o cache de documentos arquivados
|
|
81
|
+
* Delega para o plugin firestore-archive
|
|
38
82
|
*/
|
|
39
83
|
clearArchivedCache(collectionName?: string, docId?: string): Promise<void>;
|
|
84
|
+
/**
|
|
85
|
+
* Retorna o projectId do Firestore sendo arquivado
|
|
86
|
+
* (usado para organização de paths no Storage)
|
|
87
|
+
*/
|
|
88
|
+
getProjectId(): string;
|
|
40
89
|
}
|
|
90
|
+
export {};
|
|
@@ -1,40 +1,37 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
-
if (mod && mod.__esModule) return mod;
|
|
20
|
-
var result = {};
|
|
21
|
-
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
-
__setModuleDefault(result, mod);
|
|
23
|
-
return result;
|
|
24
|
-
};
|
|
25
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
3
|
exports.ArchiveService = void 0;
|
|
27
|
-
const storage_1 = require("@google-cloud/storage");
|
|
28
|
-
const zlib = __importStar(require("zlib"));
|
|
29
|
-
const stream_1 = require("stream");
|
|
30
4
|
const ArchiveConfig_1 = require("../config/ArchiveConfig");
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
5
|
+
const index_1 = require("./index");
|
|
6
|
+
/**
|
|
7
|
+
* Logger interno para padronizar logs do ArchiveService
|
|
8
|
+
*/
|
|
9
|
+
class ArchiveLogger {
|
|
10
|
+
constructor(debug) {
|
|
11
|
+
this.prefix = '[ArchiveServices]';
|
|
12
|
+
this.isDebug = debug;
|
|
13
|
+
}
|
|
14
|
+
debug(message, ...args) {
|
|
15
|
+
if (this.isDebug) {
|
|
16
|
+
console.debug(`${this.prefix} ${message}`, ...args);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
info(message, ...args) {
|
|
20
|
+
if (this.isDebug) {
|
|
21
|
+
console.info(`${this.prefix} ${message}`, ...args);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
warn(message, ...args) {
|
|
25
|
+
console.warn(`${this.prefix} ${message}`, ...args);
|
|
26
|
+
}
|
|
27
|
+
error(message, ...args) {
|
|
28
|
+
console.error(`${this.prefix} ${message}`, ...args);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
34
31
|
class ArchiveService {
|
|
35
32
|
/**
|
|
36
|
-
|
|
37
|
-
|
|
33
|
+
* Construtor privado para prevenir instanciação direta
|
|
34
|
+
*/
|
|
38
35
|
constructor() {
|
|
39
36
|
this.isInitialized = false;
|
|
40
37
|
// Construtor vazio - inicialização será feita em initialize()
|
|
@@ -67,33 +64,23 @@ class ArchiveService {
|
|
|
67
64
|
return;
|
|
68
65
|
}
|
|
69
66
|
this.config = ArchiveConfig_1.ArchiveConfig.getConfig();
|
|
70
|
-
this.
|
|
67
|
+
this.logger = new ArchiveLogger(this.config.debug);
|
|
68
|
+
// ProjectId do Firestore que está sendo arquivado (usado para paths no Storage)
|
|
71
69
|
this.projectId = this.config.projectId;
|
|
72
|
-
(
|
|
73
|
-
|
|
74
|
-
this.
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
78
|
-
// REGISTRAR O ARCHIVESERVICE COMO REPOSITORY
|
|
79
|
-
this.cacheResolver.addRepository('ArchiveService', {
|
|
80
|
-
cacheExpiresInSeconds: 3600,
|
|
81
|
-
cacheProvider: CacheProviders_1.CacheProviders.REDIS_ARCHIVE
|
|
82
|
-
});
|
|
70
|
+
if (!this.projectId) {
|
|
71
|
+
this.logger.warn('projectId não configurado - usando variável de ambiente');
|
|
72
|
+
this.projectId = process.env.FIRESTORE_PROJECTID || process.env.GCP_PROJECT || '';
|
|
73
|
+
}
|
|
74
|
+
this.logger.debug(`Configuração: projectId=${this.projectId}, enabled=${this.config.enabled}`);
|
|
83
75
|
if (!this.config.enabled) {
|
|
84
|
-
|
|
76
|
+
this.logger.info('Arquivamento desabilitado via configuração');
|
|
77
|
+
this.isInitialized = true;
|
|
85
78
|
return;
|
|
86
79
|
}
|
|
87
|
-
|
|
88
|
-
this.
|
|
89
|
-
this.bucketName = this.config.bucketName;
|
|
90
|
-
if (!this.bucketName) {
|
|
91
|
-
(0, ArchiveConfig_1.onDebugWarn)('ArchiveService: bucket_name não configurado');
|
|
92
|
-
}
|
|
93
|
-
else {
|
|
94
|
-
(0, ArchiveConfig_1.onDebugLog)(`Bucket configurado: ${this.bucketName}`);
|
|
95
|
-
}
|
|
80
|
+
if (!(0, index_1.hasArchivePlugin)()) {
|
|
81
|
+
this.logger.warn('Plugin firestore-archive não registrado - arquivamento desabilitado');
|
|
96
82
|
}
|
|
83
|
+
this.isInitialized = true;
|
|
97
84
|
}
|
|
98
85
|
static resetInstance() {
|
|
99
86
|
ArchiveService.instance = null;
|
|
@@ -101,9 +88,11 @@ class ArchiveService {
|
|
|
101
88
|
}
|
|
102
89
|
/**
|
|
103
90
|
* Verifica se o arquivamento está habilitado
|
|
91
|
+
* Requer que o plugin firestore-archive esteja registrado
|
|
104
92
|
*/
|
|
105
93
|
isEnabled() {
|
|
106
|
-
|
|
94
|
+
// Arquivamento só funciona com plugin registrado
|
|
95
|
+
return this.config.enabled && (0, index_1.hasArchivePlugin)();
|
|
107
96
|
}
|
|
108
97
|
/**
|
|
109
98
|
* Verifica se um documento está arquivado
|
|
@@ -112,43 +101,7 @@ class ArchiveService {
|
|
|
112
101
|
if (!this.isEnabled()) {
|
|
113
102
|
return false;
|
|
114
103
|
}
|
|
115
|
-
return
|
|
116
|
-
}
|
|
117
|
-
async pipeline(readStream, gunzip, writable) {
|
|
118
|
-
return new Promise((resolve, reject) => {
|
|
119
|
-
readStream.pipe(gunzip).pipe(writable);
|
|
120
|
-
writable.on('finish', resolve);
|
|
121
|
-
writable.on('error', reject);
|
|
122
|
-
});
|
|
123
|
-
}
|
|
124
|
-
/**
|
|
125
|
-
* Recupera documento arquivado em formato JSON
|
|
126
|
-
*/
|
|
127
|
-
async retrieveJsonDocument(collectionName, docId) {
|
|
128
|
-
try {
|
|
129
|
-
const filePath = `${this.projectId}/${collectionName}/${docId}.json.gz`;
|
|
130
|
-
const bucket = this.storage.bucket(this.bucketName);
|
|
131
|
-
const file = bucket.file(filePath);
|
|
132
|
-
const [exists] = await file.exists();
|
|
133
|
-
if (!exists) {
|
|
134
|
-
return null;
|
|
135
|
-
}
|
|
136
|
-
const readStream = file.createReadStream();
|
|
137
|
-
const gunzip = zlib.createGunzip();
|
|
138
|
-
const chunks = [];
|
|
139
|
-
await this.pipeline(readStream, gunzip, new stream_1.Writable({
|
|
140
|
-
write(chunk, _enc, cb) {
|
|
141
|
-
chunks.push(chunk);
|
|
142
|
-
cb();
|
|
143
|
-
}
|
|
144
|
-
}));
|
|
145
|
-
const result = Buffer.concat(chunks).toString('utf-8');
|
|
146
|
-
return JSON.parse(result);
|
|
147
|
-
}
|
|
148
|
-
catch (error) {
|
|
149
|
-
console.log(`${ArchiveConfig_1.DEBUG_PREFIX} Erro ao recuperar documento JSON arquivado ${collectionName}/${docId}:`, error);
|
|
150
|
-
return null;
|
|
151
|
-
}
|
|
104
|
+
return (0, index_1.getArchivePlugin)().isDocumentArchived(documentData);
|
|
152
105
|
}
|
|
153
106
|
/**
|
|
154
107
|
* Verifica se um documento está arquivado e recupera seus dados completos
|
|
@@ -157,45 +110,110 @@ class ArchiveService {
|
|
|
157
110
|
if (!this.isEnabled()) {
|
|
158
111
|
return null;
|
|
159
112
|
}
|
|
160
|
-
if (!this.bucketName) {
|
|
161
|
-
console.warn(`${ArchiveConfig_1.DEBUG_PREFIX} ArchiveService: bucket_name não configurado, não é possível recuperar documentos arquivados`);
|
|
162
|
-
return null;
|
|
163
|
-
}
|
|
164
113
|
const docId = doc.id;
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
114
|
+
const archivePath = typeof doc?.[index_1.ARCHIVE_METADATA_FIELDS.ARCHIVE_PATH] === 'string'
|
|
115
|
+
? doc[index_1.ARCHIVE_METADATA_FIELDS.ARCHIVE_PATH]
|
|
116
|
+
: '';
|
|
117
|
+
if (!archivePath || archivePath.trim().length === 0) {
|
|
118
|
+
throw new Error(`ArchiveService.getArchivedDocument: fbArchivePath is required. collection=${collectionName} docId=${docId}`);
|
|
119
|
+
}
|
|
120
|
+
// Delega para plugin (isEnabled já garante que existe)
|
|
121
|
+
return (0, index_1.getArchivePlugin)().getArchivedDocument({
|
|
122
|
+
collection: collectionName,
|
|
123
|
+
docId,
|
|
124
|
+
archivePath,
|
|
125
|
+
projectId: this.projectId,
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Atualiza um documento arquivado no Cloud Storage
|
|
130
|
+
* Usado quando um documento arquivado é atualizado no Firestore
|
|
131
|
+
*
|
|
132
|
+
* @param collectionName - Nome da collection
|
|
133
|
+
* @param docId - ID do documento
|
|
134
|
+
* @param newData - Novos dados a serem mesclados com o documento arquivado
|
|
135
|
+
* @param archivePath - Path completo do objeto no Storage, normalmente o `fbArchivePath` do stub.
|
|
136
|
+
* @param options - Opções de atualização
|
|
137
|
+
* @returns Resultado da operação e dados mesclados
|
|
138
|
+
*/
|
|
139
|
+
async updateArchivedDocument(collectionName, docId, newData, archivePath, options) {
|
|
140
|
+
if (!this.isEnabled()) {
|
|
141
|
+
return { result: { success: false, message: 'Arquivamento desabilitado ou plugin não registrado' } };
|
|
142
|
+
}
|
|
143
|
+
if (!archivePath || typeof archivePath !== 'string' || archivePath.trim().length === 0) {
|
|
144
|
+
throw new Error(`ArchiveService.updateArchivedDocument: fbArchivePath is required. collection=${collectionName} docId=${docId}`);
|
|
145
|
+
}
|
|
146
|
+
// Delega para plugin (isEnabled já garante que existe)
|
|
147
|
+
return (0, index_1.getArchivePlugin)().updateArchivedDocument({
|
|
148
|
+
collection: collectionName,
|
|
149
|
+
docId,
|
|
150
|
+
newData,
|
|
151
|
+
options,
|
|
152
|
+
projectId: this.projectId,
|
|
153
|
+
archivePath,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Deleta um documento arquivado do Cloud Storage
|
|
158
|
+
* Usado quando um documento é permanentemente deletado ou restaurado
|
|
159
|
+
*
|
|
160
|
+
* @param collectionName - Nome da collection
|
|
161
|
+
* @param docId - ID do documento
|
|
162
|
+
* @param archivePath - Path completo do objeto no Storage, normalmente o `fbArchivePath` do stub.
|
|
163
|
+
* @returns Resultado da operação
|
|
164
|
+
*/
|
|
165
|
+
async deleteArchivedDocument(collectionName, docId, archivePath) {
|
|
166
|
+
if (!this.isEnabled()) {
|
|
167
|
+
return { success: false, message: 'Arquivamento desabilitado ou plugin não registrado' };
|
|
185
168
|
}
|
|
186
|
-
|
|
187
|
-
|
|
169
|
+
if (!archivePath || typeof archivePath !== 'string' || archivePath.trim().length === 0) {
|
|
170
|
+
throw new Error(`ArchiveService.deleteArchivedDocument: fbArchivePath is required. collection=${collectionName} docId=${docId}`);
|
|
188
171
|
}
|
|
189
|
-
|
|
172
|
+
// Delega para plugin (isEnabled já garante que existe)
|
|
173
|
+
return (0, index_1.getArchivePlugin)().deleteArchivedDocument({
|
|
174
|
+
collection: collectionName,
|
|
175
|
+
docId,
|
|
176
|
+
projectId: this.projectId,
|
|
177
|
+
archivePath,
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Recupera dados completos de um documento arquivado e o prepara para restauração
|
|
182
|
+
* Combina os dados do stub (Firestore) com os dados arquivados (Storage)
|
|
183
|
+
*
|
|
184
|
+
* @param collectionName - Nome da collection
|
|
185
|
+
* @param stubData - Dados do stub no Firestore (inclui fbArchivedAt)
|
|
186
|
+
* @returns Dados completos mesclados ou null se não encontrado
|
|
187
|
+
*/
|
|
188
|
+
async getCompleteArchivedDocument(collectionName, stubData) {
|
|
189
|
+
if (!this.isDocumentArchived(stubData)) {
|
|
190
|
+
return stubData;
|
|
191
|
+
}
|
|
192
|
+
const archivedData = await this.getArchivedDocument(collectionName, stubData);
|
|
193
|
+
if (!archivedData) {
|
|
194
|
+
this.logger.warn(`Dados arquivados não encontrados para documento: ${collectionName}/${stubData.id}`);
|
|
195
|
+
return stubData; // Retorna stub se não encontrar dados arquivados
|
|
196
|
+
}
|
|
197
|
+
// Mesclar: dados do storage sobrescrevem o stub, exceto fbArchivedAt
|
|
198
|
+
const { fbArchivedAt } = stubData;
|
|
199
|
+
return { ...stubData, ...archivedData, fbArchivedAt };
|
|
190
200
|
}
|
|
191
201
|
/**
|
|
192
202
|
* Limpa o cache de documentos arquivados
|
|
203
|
+
* Delega para o plugin firestore-archive
|
|
193
204
|
*/
|
|
194
205
|
async clearArchivedCache(collectionName, docId) {
|
|
195
|
-
if (!this.
|
|
206
|
+
if (!this.isEnabled()) {
|
|
196
207
|
return;
|
|
197
208
|
}
|
|
198
|
-
await
|
|
209
|
+
await (0, index_1.getArchivePlugin)().invalidateCache(collectionName, docId);
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Retorna o projectId do Firestore sendo arquivado
|
|
213
|
+
* (usado para organização de paths no Storage)
|
|
214
|
+
*/
|
|
215
|
+
getProjectId() {
|
|
216
|
+
return this.projectId;
|
|
199
217
|
}
|
|
200
218
|
}
|
|
201
219
|
exports.ArchiveService = ArchiveService;
|