feat: allowing users to delete images from lists
This commit is contained in:
@ -195,7 +195,23 @@ func (m ListModel) Save(ctx context.Context, userId uuid.UUID, name string, desc
|
|||||||
return listWithItems, err
|
return listWithItems, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m ListModel) SaveInto(ctx context.Context, listId uuid.UUID, imageId uuid.UUID, schemaValues []IDValue) error {
|
func (m ListModel) SaveInto(ctx context.Context, listID uuid.UUID, imageID uuid.UUID, schemaValues []IDValue) error {
|
||||||
|
tx, err := m.dbPool.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var imageList model.ImageLists
|
||||||
|
stmt := ImageLists.INSERT(ImageLists.ListID, ImageLists.ImageID).
|
||||||
|
VALUES(listID, imageID).
|
||||||
|
RETURNING(ImageLists.ID)
|
||||||
|
|
||||||
|
err = stmt.QueryContext(ctx, m.dbPool, &imageList)
|
||||||
|
if err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return fmt.Errorf("Could not insert new list. %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
imageSchemaItems := make([]model.ImageSchemaItems, len(schemaValues))
|
imageSchemaItems := make([]model.ImageSchemaItems, len(schemaValues))
|
||||||
|
|
||||||
for i, v := range schemaValues {
|
for i, v := range schemaValues {
|
||||||
@ -205,24 +221,10 @@ func (m ListModel) SaveInto(ctx context.Context, listId uuid.UUID, imageId uuid.
|
|||||||
}
|
}
|
||||||
|
|
||||||
imageSchemaItems[i].SchemaItemID = parsedId
|
imageSchemaItems[i].SchemaItemID = parsedId
|
||||||
imageSchemaItems[i].ImageID = imageId
|
imageSchemaItems[i].ImageID = imageList.ID
|
||||||
imageSchemaItems[i].Value = &v.Value
|
imageSchemaItems[i].Value = &v.Value
|
||||||
}
|
}
|
||||||
|
|
||||||
tx, err := m.dbPool.BeginTx(ctx, nil)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
stmt := ImageLists.INSERT(ImageLists.ListID, ImageLists.ImageID).
|
|
||||||
VALUES(listId, imageId)
|
|
||||||
|
|
||||||
_, err = stmt.ExecContext(ctx, tx)
|
|
||||||
if err != nil {
|
|
||||||
tx.Rollback()
|
|
||||||
return fmt.Errorf("Could not insert new list. %s", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
insertSchemaItemsStmt := ImageSchemaItems.
|
insertSchemaItemsStmt := ImageSchemaItems.
|
||||||
INSERT(ImageSchemaItems.Value, ImageSchemaItems.SchemaItemID, ImageSchemaItems.ImageID).
|
INSERT(ImageSchemaItems.Value, ImageSchemaItems.SchemaItemID, ImageSchemaItems.ImageID).
|
||||||
MODELS(imageSchemaItems)
|
MODELS(imageSchemaItems)
|
||||||
@ -251,6 +253,18 @@ func (m ListModel) SaveProcessing(ctx context.Context, userID uuid.UUID, title s
|
|||||||
// DELETE methods
|
// DELETE methods
|
||||||
// ========================================
|
// ========================================
|
||||||
|
|
||||||
|
func (m ListModel) DeleteImage(ctx context.Context, listID uuid.UUID, imageID uuid.UUID) error {
|
||||||
|
deleteImageListStmt := ImageLists.DELETE().
|
||||||
|
WHERE(
|
||||||
|
ImageLists.ListID.EQ(UUID(listID)).
|
||||||
|
AND(ImageLists.ImageID.EQ(UUID(imageID))),
|
||||||
|
)
|
||||||
|
|
||||||
|
_, err := deleteImageListStmt.ExecContext(ctx, m.dbPool)
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
func (m ListModel) Delete(ctx context.Context, listID uuid.UUID, userID uuid.UUID) error {
|
func (m ListModel) Delete(ctx context.Context, listID uuid.UUID, userID uuid.UUID) error {
|
||||||
// First verify the list belongs to the user
|
// First verify the list belongs to the user
|
||||||
checkOwnershipStmt := Lists.
|
checkOwnershipStmt := Lists.
|
||||||
|
@ -107,7 +107,7 @@ func (m UserModel) ListWithImages(ctx context.Context, userId uuid.UUID) ([]List
|
|||||||
INNER_JOIN(Schemas, Schemas.ListID.EQ(Lists.ID)).
|
INNER_JOIN(Schemas, Schemas.ListID.EQ(Lists.ID)).
|
||||||
INNER_JOIN(SchemaItems, SchemaItems.SchemaID.EQ(Schemas.ID)).
|
INNER_JOIN(SchemaItems, SchemaItems.SchemaID.EQ(Schemas.ID)).
|
||||||
LEFT_JOIN(ImageLists, ImageLists.ListID.EQ(Lists.ID)).
|
LEFT_JOIN(ImageLists, ImageLists.ListID.EQ(Lists.ID)).
|
||||||
LEFT_JOIN(ImageSchemaItems, ImageSchemaItems.ImageID.EQ(ImageLists.ImageID)),
|
LEFT_JOIN(ImageSchemaItems, ImageSchemaItems.ImageID.EQ(ImageLists.ID)),
|
||||||
).
|
).
|
||||||
WHERE(Lists.UserID.EQ(UUID(userId)))
|
WHERE(Lists.UserID.EQ(UUID(userId)))
|
||||||
|
|
||||||
|
@ -93,7 +93,7 @@ CREATE TABLE haystack.image_schema_items (
|
|||||||
value TEXT,
|
value TEXT,
|
||||||
|
|
||||||
schema_item_id UUID NOT NULL REFERENCES haystack.schema_items (id),
|
schema_item_id UUID NOT NULL REFERENCES haystack.schema_items (id),
|
||||||
image_id UUID NOT NULL REFERENCES haystack.image (id) ON DELETE CASCADE
|
image_id UUID NOT NULL REFERENCES haystack.image_lists (id) ON DELETE CASCADE
|
||||||
);
|
);
|
||||||
|
|
||||||
/* -----| Indexes |----- */
|
/* -----| Indexes |----- */
|
||||||
|
@ -13,11 +13,15 @@ import (
|
|||||||
|
|
||||||
"github.com/charmbracelet/log"
|
"github.com/charmbracelet/log"
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
type StackHandler struct {
|
type StackHandler struct {
|
||||||
logger *log.Logger
|
logger *log.Logger
|
||||||
stackModel models.ListModel
|
|
||||||
|
imageModel models.ImageModel
|
||||||
|
stackModel models.ListModel
|
||||||
|
|
||||||
limitsManager limits.LimitsManagerMethods
|
limitsManager limits.LimitsManagerMethods
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -94,6 +98,47 @@ func (h *StackHandler) deleteStack(w http.ResponseWriter, r *http.Request) {
|
|||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *StackHandler) deleteImageFromStack(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
stringImageID := chi.URLParam(r, "imageID")
|
||||||
|
stringListID := chi.URLParam(r, "listID")
|
||||||
|
|
||||||
|
imageID, err := uuid.Parse(stringImageID)
|
||||||
|
if err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
listID, err := uuid.Parse(stringListID)
|
||||||
|
if err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: this should be extracted into a middleware of sorts
|
||||||
|
userID, err := middleware.GetUserID(ctx, h.logger, w)
|
||||||
|
if err != nil {
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
isAuthorized := h.imageModel.IsUserAuthorized(ctx, imageID, userID)
|
||||||
|
if !isAuthorized {
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = h.stackModel.DeleteImage(ctx, listID, imageID)
|
||||||
|
if err != nil {
|
||||||
|
h.logger.Warn("failed to delete image from list", "error", err)
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
type CreateStackBody struct {
|
type CreateStackBody struct {
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
|
|
||||||
@ -149,15 +194,18 @@ func (h *StackHandler) CreateRoutes(r chi.Router) {
|
|||||||
r.Post("/", middleware.WithLimit(h.logger, h.limitsManager.HasReachedStackLimit, middleware.WithValidatedPost(h.createStack)))
|
r.Post("/", middleware.WithLimit(h.logger, h.limitsManager.HasReachedStackLimit, middleware.WithValidatedPost(h.createStack)))
|
||||||
r.Patch("/{listID}", middleware.WithValidatedPost(h.editStack))
|
r.Patch("/{listID}", middleware.WithValidatedPost(h.editStack))
|
||||||
r.Delete("/{listID}", h.deleteStack)
|
r.Delete("/{listID}", h.deleteStack)
|
||||||
|
r.Delete("/{listID}/{imageID}", h.deleteImageFromStack)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func CreateStackHandler(db *sql.DB, limitsManager limits.LimitsManagerMethods) StackHandler {
|
func CreateStackHandler(db *sql.DB, limitsManager limits.LimitsManagerMethods) StackHandler {
|
||||||
stackModel := models.NewListModel(db)
|
stackModel := models.NewListModel(db)
|
||||||
|
imageModel := models.NewImageModel(db)
|
||||||
logger := log.New(os.Stdout).WithPrefix("Stacks")
|
logger := log.New(os.Stdout).WithPrefix("Stacks")
|
||||||
|
|
||||||
return StackHandler{
|
return StackHandler{
|
||||||
logger,
|
logger,
|
||||||
|
imageModel,
|
||||||
stackModel,
|
stackModel,
|
||||||
limitsManager,
|
limitsManager,
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,7 @@ import {
|
|||||||
createResource,
|
createResource,
|
||||||
useContext,
|
useContext,
|
||||||
} from "solid-js";
|
} from "solid-js";
|
||||||
import { deleteImage, getUserImages, JustTheImageWhatAreTheseNames } from "../network";
|
import { deleteImage, deleteImageFromStack, getUserImages, JustTheImageWhatAreTheseNames } from "../network";
|
||||||
|
|
||||||
export type SearchImageStore = {
|
export type SearchImageStore = {
|
||||||
imagesByDate: Accessor<
|
imagesByDate: Accessor<
|
||||||
@ -24,6 +24,7 @@ export type SearchImageStore = {
|
|||||||
|
|
||||||
onRefetchImages: () => void;
|
onRefetchImages: () => void;
|
||||||
onDeleteImage: (imageID: string) => void;
|
onDeleteImage: (imageID: string) => void;
|
||||||
|
onDeleteImageFromStack: (stackID: string, imageID: string) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
const SearchImageContext = createContext<SearchImageStore>();
|
const SearchImageContext = createContext<SearchImageStore>();
|
||||||
@ -71,6 +72,9 @@ export const SearchImageContextProvider: Component<ParentProps> = (props) => {
|
|||||||
onRefetchImages: refetch,
|
onRefetchImages: refetch,
|
||||||
onDeleteImage: (imageID: string) => {
|
onDeleteImage: (imageID: string) => {
|
||||||
deleteImage(imageID).then(refetch);
|
deleteImage(imageID).then(refetch);
|
||||||
|
},
|
||||||
|
onDeleteImageFromStack: (stackID: string, imageID: string) => {
|
||||||
|
deleteImageFromStack(stackID, imageID).then(refetch);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
@ -6,8 +6,8 @@ import {
|
|||||||
literal,
|
literal,
|
||||||
null_,
|
null_,
|
||||||
nullable,
|
nullable,
|
||||||
parse,
|
|
||||||
pipe,
|
pipe,
|
||||||
|
safeParse,
|
||||||
strictObject,
|
strictObject,
|
||||||
string,
|
string,
|
||||||
transform,
|
transform,
|
||||||
@ -64,8 +64,14 @@ export const sendImageFile = async (
|
|||||||
request.headers.set("Content-Type", "application/oclet-stream");
|
request.headers.set("Content-Type", "application/oclet-stream");
|
||||||
|
|
||||||
const res = await fetch(request).then((res) => res.json());
|
const res = await fetch(request).then((res) => res.json());
|
||||||
|
const parsedRes = safeParse(sendImageResponseValidator, res);
|
||||||
|
|
||||||
return parse(sendImageResponseValidator, res);
|
if (!parsedRes.success) {
|
||||||
|
console.log(parsedRes.issues)
|
||||||
|
throw new Error(JSON.stringify(parsedRes.issues));
|
||||||
|
}
|
||||||
|
|
||||||
|
return parsedRes.output;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const deleteImage = async (
|
export const deleteImage = async (
|
||||||
@ -79,6 +85,15 @@ export const deleteImage = async (
|
|||||||
await fetch(request);
|
await fetch(request);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const deleteImageFromStack = async (listID: string, imageID: string): Promise<void> => {
|
||||||
|
const request = getBaseAuthorizedRequest({
|
||||||
|
path: `stacks/${listID}/${imageID}`,
|
||||||
|
method: "DELETE",
|
||||||
|
});
|
||||||
|
|
||||||
|
await fetch(request);
|
||||||
|
}
|
||||||
|
|
||||||
export class ImageLimitReached extends Error {
|
export class ImageLimitReached extends Error {
|
||||||
constructor() {
|
constructor() {
|
||||||
super();
|
super();
|
||||||
@ -104,7 +119,13 @@ export const sendImage = async (
|
|||||||
|
|
||||||
const res = await rawRes.json();
|
const res = await rawRes.json();
|
||||||
|
|
||||||
return parse(sendImageResponseValidator, res);
|
const parsedRes = safeParse(sendImageResponseValidator, res);
|
||||||
|
if (!parsedRes.success) {
|
||||||
|
console.log(parsedRes.issues)
|
||||||
|
throw new Error(JSON.stringify(parsedRes.issues));
|
||||||
|
}
|
||||||
|
|
||||||
|
return parsedRes.output;
|
||||||
};
|
};
|
||||||
|
|
||||||
const imageMetaValidator = strictObject({
|
const imageMetaValidator = strictObject({
|
||||||
@ -207,7 +228,13 @@ export const getUserImages = async (): Promise<
|
|||||||
|
|
||||||
console.log("Backend response: ", res);
|
console.log("Backend response: ", res);
|
||||||
|
|
||||||
return parse(imageRequestValidator, res);
|
const parsedRes = safeParse(imageRequestValidator, res);
|
||||||
|
if (!parsedRes.success) {
|
||||||
|
console.log(parsedRes.issues)
|
||||||
|
throw new Error(JSON.stringify(parsedRes.issues));
|
||||||
|
}
|
||||||
|
|
||||||
|
return parsedRes.output;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const postLogin = async (email: string): Promise<void> => {
|
export const postLogin = async (email: string): Promise<void> => {
|
||||||
@ -237,7 +264,13 @@ export const postCode = async (
|
|||||||
|
|
||||||
const res = await fetch(request).then((res) => res.json());
|
const res = await fetch(request).then((res) => res.json());
|
||||||
|
|
||||||
return parse(codeValidator, res);
|
const parsedRes = safeParse(codeValidator, res);
|
||||||
|
if (!parsedRes.success) {
|
||||||
|
console.log(parsedRes.issues)
|
||||||
|
throw new Error(JSON.stringify(parsedRes.issues));
|
||||||
|
}
|
||||||
|
|
||||||
|
return parsedRes.output;
|
||||||
};
|
};
|
||||||
|
|
||||||
export class ReachedListLimit extends Error {
|
export class ReachedListLimit extends Error {
|
||||||
|
@ -1,12 +1,56 @@
|
|||||||
import { useSearchImageContext } from "@contexts/SearchImageContext";
|
import { useSearchImageContext } from "@contexts/SearchImageContext";
|
||||||
import { useParams } from "@solidjs/router";
|
import { useParams } from "@solidjs/router";
|
||||||
import { Component, For, Show } from "solid-js";
|
import { Component, For, Show, createSignal } from "solid-js";
|
||||||
import { base } from "../../network";
|
import { base } from "../../network";
|
||||||
|
import { Dialog } from "@kobalte/core";
|
||||||
|
|
||||||
|
const DeleteButton: Component<{ onDelete: () => void }> = (props) => {
|
||||||
|
const [isOpen, setIsOpen] = createSignal(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
aria-label="Delete image from list"
|
||||||
|
class="text-white bg-red-600 hover:bg-red-700 rounded px-2 py-1 text-sm"
|
||||||
|
onClick={() => setIsOpen(true)}
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<Dialog.Root open={isOpen()} onOpenChange={setIsOpen}>
|
||||||
|
<Dialog.Portal>
|
||||||
|
<Dialog.Overlay class="fixed inset-0 bg-black bg-opacity-50" />
|
||||||
|
<div class="fixed inset-0 z-50 flex items-center justify-center p-4">
|
||||||
|
<Dialog.Content class="bg-white rounded-lg shadow-xl max-w-md w-full p-6">
|
||||||
|
<Dialog.Title class="text-lg font-bold mb-2">
|
||||||
|
Confirm Delete
|
||||||
|
</Dialog.Title>
|
||||||
|
<Dialog.Description class="mb-4">
|
||||||
|
Are you sure you want to delete this image from
|
||||||
|
this list?
|
||||||
|
</Dialog.Description>
|
||||||
|
<div class="flex justify-end gap-2">
|
||||||
|
<Dialog.CloseButton>
|
||||||
|
<button class="px-4 py-2 bg-gray-300 rounded hover:bg-gray-400">
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</Dialog.CloseButton>
|
||||||
|
<button class="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700" onClick={props.onDelete}>
|
||||||
|
Confirm
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</Dialog.Content>
|
||||||
|
</div>
|
||||||
|
</Dialog.Portal>
|
||||||
|
</Dialog.Root>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
export const List: Component = () => {
|
export const List: Component = () => {
|
||||||
const { listId } = useParams();
|
const { listId } = useParams();
|
||||||
|
|
||||||
const { lists } = useSearchImageContext();
|
const { lists, onDeleteImageFromStack } = useSearchImageContext();
|
||||||
|
|
||||||
const list = () => lists().find((l) => l.ID === listId);
|
const list = () => lists().find((l) => l.ID === listId);
|
||||||
|
|
||||||
@ -24,14 +68,13 @@ export const List: Component = () => {
|
|||||||
<For each={l().Schema.SchemaItems}>
|
<For each={l().Schema.SchemaItems}>
|
||||||
{(item, index) => (
|
{(item, index) => (
|
||||||
<th
|
<th
|
||||||
class={`px-6 py-4 text-left text-sm font-semibold text-neutral-900 min-w-32 ${
|
class={`px-6 py-4 text-left text-sm font-semibold text-neutral-900 min-w-32 ${index() <
|
||||||
index() <
|
|
||||||
l().Schema.SchemaItems
|
l().Schema.SchemaItems
|
||||||
.length -
|
.length -
|
||||||
1
|
1
|
||||||
? "border-r border-neutral-200"
|
? "border-r border-neutral-200"
|
||||||
: ""
|
: ""
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{item.Item}
|
{item.Item}
|
||||||
</th>
|
</th>
|
||||||
@ -43,17 +86,16 @@ export const List: Component = () => {
|
|||||||
<For each={l().Images}>
|
<For each={l().Images}>
|
||||||
{(image, rowIndex) => (
|
{(image, rowIndex) => (
|
||||||
<tr
|
<tr
|
||||||
class={`hover:bg-neutral-50 transition-colors ${
|
class={`hover:bg-neutral-50 transition-colors ${rowIndex() % 2 === 0
|
||||||
rowIndex() % 2 === 0
|
? "bg-white"
|
||||||
? "bg-white"
|
: "bg-neutral-25"
|
||||||
: "bg-neutral-25"
|
}`}
|
||||||
}`}
|
|
||||||
>
|
>
|
||||||
<td class="px-6 py-4 border-r border-neutral-200">
|
<td class="px-6 py-4 border-r border-neutral-200">
|
||||||
<div class="w-32 h-24 overflow-hidden rounded-lg">
|
<div class="flex items-center gap-2">
|
||||||
<a
|
<a
|
||||||
href={`/image/${image.ImageID}`}
|
href={`/image/${image.ImageID}`}
|
||||||
class="w-full h-full flex justify-center"
|
class="w-32 h-24 flex justify-center rounded-lg overflow-hidden"
|
||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
class="w-full h-full object-cover rounded-lg"
|
class="w-full h-full object-cover rounded-lg"
|
||||||
@ -61,18 +103,18 @@ export const List: Component = () => {
|
|||||||
alt="List item"
|
alt="List item"
|
||||||
/>
|
/>
|
||||||
</a>
|
</a>
|
||||||
|
<DeleteButton onDelete={() => onDeleteImageFromStack(l().ID, image.ImageID)} />
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<For each={image.Items}>
|
<For each={image.Items}>
|
||||||
{(item, colIndex) => (
|
{(item, colIndex) => (
|
||||||
<td
|
<td
|
||||||
class={`px-6 py-4 text-sm text-neutral-700 ${
|
class={`px-6 py-4 text-sm text-neutral-700 ${colIndex() <
|
||||||
colIndex() <
|
|
||||||
image.Items.length -
|
image.Items.length -
|
||||||
1
|
1
|
||||||
? "border-r border-neutral-200"
|
? "border-r border-neutral-200"
|
||||||
: ""
|
: ""
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
class="max-w-xs truncate"
|
class="max-w-xs truncate"
|
||||||
|
Reference in New Issue
Block a user