Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

Create assets with patches (#1633)

Bogdan Chadkin438af049bd54
diff --git a/apps/builder/app/builder/shared/assets/use-assets.tsx b/apps/builder/app/builder/shared/assets/use-assets.tsx
index a1cd644206..f166452d5e 100644
--- a/apps/builder/app/builder/shared/assets/use-assets.tsx
+++ b/apps/builder/app/builder/shared/assets/use-assets.tsx
@@ -38,7 +38,7 @@ const setAsset = (asset: Asset) => {
};
type FileData = {
- id: string;
+ assetId: string;
type: AssetType;
file: File;
objectURL: string;
@@ -47,7 +47,7 @@ type FileData = {
const getFilesData = (type: AssetType, files: File[]): FileData[] => {
return files.map((file) => {
return {
- id: crypto.randomUUID(),
+ assetId: crypto.randomUUID(),
type,
file,
objectURL: URL.createObjectURL(file),
@@ -62,10 +62,10 @@ const addUploadingFilesData = (filesData: FileData[]) => {
uploadingFilesDataStore.set([...uploadingFilesData, ...filesData]);
};
-const deleteUploadingFileData = (id: FileData["id"]) => {
+const deleteUploadingFileData = (id: FileData["assetId"]) => {
const uploadingFilesData = uploadingFilesDataStore.get();
uploadingFilesDataStore.set(
- uploadingFilesData.filter((fileData) => fileData.id !== id)
+ uploadingFilesData.filter((fileData) => fileData.assetId !== id)
);
};
@@ -73,12 +73,12 @@ const assetContainersStore = computed(
[assetsStore, uploadingFilesDataStore],
(assets, uploadingFilesData) => {
const uploadingAssets = new Map<PreviewAsset["id"], AssetContainer>();
- for (const { id, type, file, objectURL } of uploadingFilesData) {
- uploadingAssets.set(id, {
+ for (const { assetId, type, file, objectURL } of uploadingFilesData) {
+ uploadingAssets.set(assetId, {
status: "uploading",
objectURL: objectURL,
asset: {
- id,
+ id: assetId,
type,
format: file.type.split("/")[1],
name: file.name,
@@ -109,14 +109,12 @@ export type UploadData = ActionData;
const uploadAsset = async ({
authToken,
projectId,
- assetId,
file,
onCompleted,
onError,
}: {
authToken: undefined | string;
projectId: string;
- assetId: string;
file: File;
onCompleted: (data: UploadData) => void;
onError: (error: string) => void;
@@ -124,7 +122,6 @@ const uploadAsset = async ({
try {
const metaFormData = new FormData();
metaFormData.append("projectId", projectId);
- metaFormData.append("assetId", assetId);
metaFormData.append("type", file.type);
// sanitizeS3Key here is just because of https://github.com/remix-run/remix/issues/4443
// should be removed after fix
@@ -174,8 +171,8 @@ export const useUploadAsset = () => {
return;
}
- // update store with new asset
- setAsset(uploadedAsset);
+ // update store with new asset and set current id
+ setAsset({ ...uploadedAsset, id: assetId });
};
const uploadAssets = (type: AssetType, files: File[]) => {
@@ -188,14 +185,13 @@ export const useUploadAsset = () => {
const filesData = getFilesData(type, files);
addUploadingFilesData(filesData);
- stubAssets(filesData.map((fileData) => fileData.id));
+ stubAssets(filesData.map((fileData) => fileData.assetId));
for (const fileData of filesData) {
- const assetId = fileData.id;
+ const assetId = fileData.assetId;
uploadAsset({
authToken,
projectId,
- assetId,
file: fileData.file,
onCompleted: (data) => {
URL.revokeObjectURL(fileData.objectURL);
diff --git a/apps/builder/app/routes/rest.assets.tsx b/apps/builder/app/routes/rest.assets.tsx
index dd067cee33..3f3c7ebbc9 100644
--- a/apps/builder/app/routes/rest.assets.tsx
+++ b/apps/builder/app/routes/rest.assets.tsx
@@ -28,21 +28,14 @@ export const action = async (props: ActionArgs) => {
if (request.method === "POST") {
const formData = await request.formData();
const projectId = formData.get("projectId") as string;
- const assetId = formData.get("assetId") as string;
const type = formData.get("type") as string;
const filename = formData.get("filename") as string;
- if (
- projectId === null ||
- assetId === null ||
- type === null ||
- filename === null
- ) {
+ if (projectId === null || type === null || filename === null) {
throw Error("Project id, asset id or filename are missing");
}
const name = await createUploadName(
{
projectId,
- assetId,
type,
filename,
maxAssetsPerProject: MaxAssets.parse(env.MAX_ASSETS_PER_PROJECT),
diff --git a/packages/asset-uploader/src/delete.ts b/packages/asset-uploader/src/delete.ts
index 3af986ee42..5dd7060fa6 100644
--- a/packages/asset-uploader/src/delete.ts
+++ b/packages/asset-uploader/src/delete.ts
@@ -6,7 +6,6 @@ import {
} from "@webstudio-is/trpc-interface/index.server";
import type { AssetClient } from "./client";
import type { Asset } from "./schema";
-import { formatAsset } from "./utils/format-asset";
export const deleteAssets = async (
props: {
@@ -15,7 +14,7 @@ export const deleteAssets = async (
},
context: AppContext,
client: AssetClient
-): Promise<Array<Asset>> => {
+) => {
const canDelete = await authorizeProject.hasProjectPermit(
{ projectId: props.projectId, permit: "edit" },
context
@@ -62,6 +61,4 @@ export const deleteAssets = async (
for (const name of unusedFileNames) {
await client.deleteFile(name);
}
-
- return assets.map((asset) => formatAsset(asset, asset.file));
};
diff --git a/packages/asset-uploader/src/patch.ts b/packages/asset-uploader/src/patch.ts
index 5f02675670..0cc5b5b067 100644
--- a/packages/asset-uploader/src/patch.ts
+++ b/packages/asset-uploader/src/patch.ts
@@ -1,5 +1,5 @@
import { type Patch, applyPatches } from "immer";
-import type { Project } from "@webstudio-is/prisma-client";
+import { type Project, prisma } from "@webstudio-is/prisma-client";
import {
type AppContext,
authorizeProject,
@@ -9,6 +9,10 @@ import { deleteAssets } from "./delete";
import { loadAssetsByProject } from "./db/load";
import type { AssetClient } from "./client";
+/**
+ * patchAssets can only delete or add assets
+ * update patches are ignored
+ */
export const patchAssets = async (
{ projectId }: { projectId: Project["id"] },
patches: Array<Patch>,
@@ -40,4 +44,31 @@ export const patchAssets = async (
if (deletedAssetIds.length !== 0) {
deleteAssets({ projectId, ids: deletedAssetIds }, context, assetClient);
}
+
+ // add new assets found in patched version
+ const addedAssets: Asset[] = [];
+ for (const [assetId, asset] of patchedAssets) {
+ // skip stubbed assets
+ if (asset === undefined) {
+ continue;
+ }
+ if (assets.has(assetId) === false) {
+ addedAssets.push(asset);
+ }
+ }
+ if (addedAssets.length !== 0) {
+ await prisma.asset.createMany({
+ data: addedAssets.map((asset) => ({
+ id: asset.id,
+ projectId: asset.projectId,
+ name: asset.name,
+ // @todo remove once legacy fields are removed from schema
+ location: asset.location,
+ size: asset.size,
+ format: asset.format,
+ meta: JSON.stringify(asset.meta),
+ status: "UPLOADED",
+ })),
+ });
+ }
};
diff --git a/packages/asset-uploader/src/upload.ts b/packages/asset-uploader/src/upload.ts
index 3bb26f3331..a9658f8c47 100644
--- a/packages/asset-uploader/src/upload.ts
+++ b/packages/asset-uploader/src/upload.ts
@@ -11,7 +11,6 @@ import { formatAsset } from "./utils/format-asset";
type UploadData = {
projectId: string;
- assetId: string;
type: string;
filename: string;
maxAssetsPerProject: number;
@@ -23,7 +22,7 @@ export const createUploadName = async (
data: UploadData,
context: AppContext
) => {
- const { projectId, maxAssetsPerProject, assetId, type, filename } = data;
+ const { projectId, maxAssetsPerProject, type, filename } = data;
const canEdit = await authorizeProject.hasProjectPermit(
{ projectId, permit: "edit" },
context
@@ -62,7 +61,9 @@ export const createUploadName = async (
* it's probable that the user can exceed the limit a little bit.
* So it can be a little bit strange that the limit is 5 but the user already has 7.
**/
- throw new Error(`The maximum number of assets per project is ${count}.`);
+ throw new Error(
+ `The maximum number of assets per project is ${maxAssetsPerProject}.`
+ );
}
/**
@@ -75,25 +76,14 @@ export const createUploadName = async (
* "SELECT id FROM "Project" where id=? FOR UPDATE;" is shareable between sqlite and postgres.
**/
const name = getUniqueFilename(sanitizeS3Key(filename));
- await prisma.asset.create({
+ await prisma.file.create({
data: {
- id: assetId,
- projectId,
- location: "REMOTE",
- file: {
- create: {
- name,
- status: "UPLOADING",
- // store content type in related field
- format: type,
- size: 0,
- uploaderProjectId: projectId,
- },
- },
- // @todo remove once legacy fields are removed from schema
+ name,
status: "UPLOADING",
+ // store content type in related field
format: type,
size: 0,
+ uploaderProjectId: projectId,
},
});
return name;
@@ -104,60 +94,48 @@ export const uploadFile = async (
data: ReadableStream<Uint8Array>,
client: AssetClient
) => {
- const asset = await prisma.asset.findFirst({
- select: {
- id: true,
- projectId: true,
- file: true,
- },
+ const file = await prisma.file.findFirst({
where: {
name,
- file: {
- status: "UPLOADING",
- createdAt: { gt: new Date(Date.now() - UPLOADING_STALE_TIMEOUT) },
- },
+ status: "UPLOADING",
+ createdAt: { gt: new Date(Date.now() - UPLOADING_STALE_TIMEOUT) },
},
});
- if (asset === null) {
+ if (file === null) {
throw Error("File already uploaded or url is expired");
}
try {
const assetData = await client.uploadFile(
name,
- asset.file.format,
+ file.format,
// global web streams types do not define ReadableStream as async iterable
data as unknown as AsyncIterable<Uint8Array>
);
const { meta, format, location, size } = assetData;
- const dbAsset = await prisma.asset.update({
- select: {
- file: true,
- id: true,
- projectId: true,
- name: true,
- location: true,
- },
+ const dbFile = await prisma.file.update({
where: {
- id_projectId: { id: asset.id, projectId: asset.projectId },
+ name,
},
data: {
- location,
- file: {
- update: {
- size,
- format,
- meta: JSON.stringify(meta),
- status: "UPLOADED",
- },
- },
+ size,
+ format,
+ meta: JSON.stringify(meta),
+ status: "UPLOADED",
},
});
- return formatAsset(dbAsset, dbAsset.file);
+ return formatAsset(
+ {
+ id: "",
+ projectId: dbFile.uploaderProjectId as string,
+ location,
+ },
+ dbFile
+ );
} catch (error) {
- await prisma.asset.delete({
+ await prisma.file.delete({
where: {
- id_projectId: { id: asset.id, projectId: asset.projectId },
+ name,
},
});
diff --git a/packages/asset-uploader/src/utils/format-asset.ts b/packages/asset-uploader/src/utils/format-asset.ts
index 1ecb8b3292..b00f0e859b 100644
--- a/packages/asset-uploader/src/utils/format-asset.ts
+++ b/packages/asset-uploader/src/utils/format-asset.ts
@@ -9,7 +9,7 @@ import { type Asset, ImageMeta } from "../schema";
// @todo remove once legacy fields are removed from schema
type DbAssetWithoutOldFields = Omit<
DbAsset,
- "size" | "format" | "meta" | "status" | "description" | "createdAt"
+ "name" | "size" | "format" | "meta" | "status" | "description" | "createdAt"
>;
export const formatAsset = (