67 lines
2.1 KiB
TypeScript
67 lines
2.1 KiB
TypeScript
import { Storage } from "@google-cloud/storage";
|
|
import { Files } from "@google/genai";
|
|
import zlib from "zlib";
|
|
import { CLOUD_STORAGE_LOG_FOLDER_NAME } from "../../serverConfig";
|
|
|
|
const csClient = new Storage({projectId: process.env.PROJECT_ID});
|
|
const BUCKET_NAME = process.env.CLOUD_STORAGE_BUCKET_NAME || '';
|
|
const bucket = csClient.bucket(BUCKET_NAME);
|
|
|
|
export const storageController = {
|
|
saveToGCS: async(folder: string, filename: string, content: any, contentType: string) => {
|
|
const file = bucket.file((`${folder}/${filename}`));
|
|
await file.save(content, {
|
|
contentType: contentType,
|
|
})
|
|
},
|
|
loadFromGCS: async(folder: string, filename: string): Promise<string | null> => {
|
|
const file = bucket.file(`${folder}/${filename}`);
|
|
console.log("loading file:", `${folder}/${filename}`);
|
|
try {
|
|
const [data] = await file.download();
|
|
return zlib.gunzipSync(data).toString("utf-8");
|
|
} catch (err: any) {
|
|
return null;
|
|
}
|
|
},
|
|
loadJsonFromGCS: async(folder: string, filename: string): Promise<string | null> => {
|
|
const file = bucket.file(`${folder}/${filename}`);
|
|
// console.log("loading file:", file.name);
|
|
try {
|
|
const [data] = await file.download();
|
|
return data.toString("utf-8");
|
|
} catch (err: any) {
|
|
return null;
|
|
}
|
|
},
|
|
existsInGCS: async(folder: string, filename: string): Promise<boolean> => {
|
|
const file = bucket.file((`${folder}/${filename}`));
|
|
console.log("checking file:", file.name);
|
|
try {
|
|
const [exist] = await file.exists();
|
|
return exist;
|
|
} catch (err: any) {
|
|
return false;
|
|
}
|
|
},
|
|
getFileList: async(): Promise<string[] | null> => {
|
|
try {
|
|
const results = await bucket.getFiles({
|
|
prefix: 'request_log/',
|
|
});
|
|
const files = results[0];
|
|
files.sort((a, b) => {
|
|
if(!a.metadata.timeCreated || !b.metadata.timeCreated) return 0;
|
|
const timeA = new Date(a.metadata.timeCreated).getTime();
|
|
const timeB = new Date(b.metadata.timeCreated).getTime();
|
|
return timeA - timeB;
|
|
});
|
|
// for(const f of files[0]) {
|
|
// list.push(f.name);
|
|
// }
|
|
return files.map((f) => f.name);
|
|
} catch(error) {
|
|
return null;
|
|
}
|
|
}
|
|
};
|