Skip to content

Commit

Permalink
Add note inside action
Browse files Browse the repository at this point in the history
  • Loading branch information
pkirilin committed May 26, 2024
1 parent f00d296 commit 7dbc0e3
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 11 deletions.
1 change: 1 addition & 0 deletions src/frontend/src/features/note/addEdit/lib/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './mapping';
export * from './useAddProductIfNotExists';
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { store } from '@/app/store';
import { type CreateProductRequest, productApi, type productModel } from '@/entities/product';

const toCreateProductRequest = ({
type AddProductIfNotExistsFn = (product: productModel.AutocompleteOption) => Promise<number>;

const mapToCreateProductRequest = ({
name,
caloriesCost,
defaultQuantity,
Expand All @@ -12,7 +15,19 @@ const toCreateProductRequest = ({
categoryId: category?.id ?? 0,
});

type AddProductIfNotExistsFn = (product: productModel.AutocompleteOption) => Promise<number>;
export const addProductIfNotExists: AddProductIfNotExistsFn = async product => {
if (!product.freeSolo) {
return product.id;
}

const request = mapToCreateProductRequest(product);

const { id } = await store
.dispatch(productApi.endpoints.createProduct.initiate(request))
.unwrap();

return id;
};

export const useAddProductIfNotExists = (): AddProductIfNotExistsFn => {
const [createProduct] = productApi.useCreateProductMutation();
Expand All @@ -22,8 +37,8 @@ export const useAddProductIfNotExists = (): AddProductIfNotExistsFn => {
return product.id;
}

const createProductRequest = toCreateProductRequest(product);
const { id } = await createProduct(createProductRequest).unwrap();
const request = mapToCreateProductRequest(product);
const { id } = await createProduct(request).unwrap();
return id;
};
};
10 changes: 3 additions & 7 deletions src/frontend/src/pages/notes/ui/NewByPhoto.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,9 @@ export const action: ActionFunction = async ({ request, params }) => {
const pageId = Number(params.id);
const formData = await request.formData();
const note = addEditNoteLib.mapNoteFromFormData(formData);

if (note.product.freeSolo) {
// TODO: create product, then create note using received product id
return redirect(`/pages/${pageId}`);
}

// TODO: create note
const productId = await addEditNoteLib.addProductIfNotExists(note.product);
const createNoteRequest = addEditNoteLib.mapToCreateNoteRequest(note, productId);
await store.dispatch(noteApi.endpoints.createNote.initiate(createNoteRequest));
return redirect(`/pages/${pageId}`);
};

Expand Down

0 comments on commit 7dbc0e3

Please sign in to comment.