longcelot-sheet-db
Version:
Google Sheets-backed staging database adapter for Node.js with schema-first design
53 lines • 2.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DriveStorageAdapter = void 0;
const SchemaError_1 = require("../errors/SchemaError");
class DriveStorageAdapter {
constructor(options) {
/** Cached folder IDs: folder path -> Drive folder ID */
this._cache = new Map();
this.defaultFolder = options?.folder ?? 'uploads';
}
/** Called by SheetAdapter at construction time — injects the shared SheetClient. */
_setClient(client) {
this._client = client;
}
get client() {
if (!this._client) {
throw new SchemaError_1.SchemaError('DriveStorageAdapter has no client. Pass it as the storage option to createSheetAdapter().');
}
return this._client;
}
async upload(file, options) {
const folderPath = options.folder ?? this.defaultFolder;
const folderId = await this.resolveFolder(folderPath);
const fileId = await this.client.uploadFile(file, options.filename, options.mimeType, folderId, options.public);
return `https://drive.google.com/uc?id=${fileId}`;
}
async delete(url) {
const match = url.match(/[?&]id=([^&]+)/);
if (!match)
return;
await this.client.deleteFile(match[1]);
}
async resolveFolder(folderPath) {
if (this._cache.has(folderPath))
return this._cache.get(folderPath);
const segments = folderPath.split('/').filter(Boolean);
let parentId;
for (const segment of segments) {
const cacheKey = parentId ? `${parentId}/${segment}` : segment;
if (this._cache.has(cacheKey)) {
parentId = this._cache.get(cacheKey);
}
else {
parentId = await this.client.findOrCreateFolder(segment, parentId);
this._cache.set(cacheKey, parentId);
}
}
this._cache.set(folderPath, parentId);
return parentId;
}
}
exports.DriveStorageAdapter = DriveStorageAdapter;
//# sourceMappingURL=driveStorageAdapter.js.map