feat: add publish app
This commit is contained in:
74
src/routes/page/module/cache-file.ts
Normal file
74
src/routes/page/module/cache-file.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import { useFileStore } from '@abearxiong/use-file-store';
|
||||
import { PageModel } from '../models/index.ts';
|
||||
import { ContainerModel } from '@/routes/container/models/index.ts';
|
||||
import { Op } from 'sequelize';
|
||||
import { getContainerData } from './get-container.ts';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { getHTML, getDataJs } from './file-template.ts';
|
||||
import { minioClient } from '@/app.ts';
|
||||
import { bucketName } from '@/modules/minio.ts';
|
||||
import { getContentType } from '@/utils/get-content-type.ts';
|
||||
export const cacheFile = useFileStore('cache-file', {
|
||||
needExists: true,
|
||||
});
|
||||
|
||||
export const getDeck = async (page: PageModel) => {
|
||||
const { data } = page;
|
||||
const { nodes = [], edges } = data;
|
||||
const containerList = nodes
|
||||
.map((item) => {
|
||||
const { data } = item;
|
||||
return data?.cid;
|
||||
})
|
||||
.filter((item) => item);
|
||||
const quchong = Array.from(new Set(containerList));
|
||||
const containers = await ContainerModel.findAll({
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: quchong,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const pageData = {
|
||||
page,
|
||||
containerList: containers,
|
||||
};
|
||||
return pageData;
|
||||
};
|
||||
|
||||
export const cachePage = async (page: PageModel, opts: { tokenUser: any; key; version }) => {
|
||||
const _result = await getDeck(page);
|
||||
const result = getContainerData(_result);
|
||||
const html = getHTML({ rootId: page.id, title: page?.publish?.key });
|
||||
const dataJs = getDataJs(result);
|
||||
const htmlPath = path.resolve(cacheFile, `${page.id}.html`);
|
||||
const dataJsPath = path.resolve(cacheFile, `${page.id}.js`);
|
||||
fs.writeFileSync(htmlPath, html);
|
||||
fs.writeFileSync(dataJsPath, dataJs);
|
||||
const minioHTML = await uploadMinio({ ...opts, path: `index.html`, filePath: htmlPath });
|
||||
const minioData = await uploadMinio({ ...opts, path: `data.js`, filePath: dataJsPath });
|
||||
return [
|
||||
{
|
||||
name: 'index.html',
|
||||
path: minioHTML,
|
||||
},
|
||||
{
|
||||
name: 'data.js',
|
||||
path: minioData,
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
export const uploadMinio = async ({ tokenUser, key, version, path, filePath }) => {
|
||||
const minioPath = `${tokenUser.username}/${key}/${version}/${path}`;
|
||||
const isHTML = filePath.endsWith('.html');
|
||||
await minioClient.fPutObject(bucketName, minioPath, filePath, {
|
||||
'Content-Type': getContentType(filePath),
|
||||
'app-source': 'user-app',
|
||||
'Cache-Control': isHTML ? 'no-cache' : 'max-age=31536000, immutable', // 缓存一年
|
||||
});
|
||||
fs.unlinkSync(filePath); // 删除临时文件
|
||||
return minioPath;
|
||||
};
|
||||
Reference in New Issue
Block a user