2023-04-23 08:26:39 -05:00
// Copyright (C) 2022-present Daniel31x13 <daniel31x13@gmail.com>
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
2023-02-18 21:32:02 -06:00
import { create } from "zustand" ;
import { Collection } from "@prisma/client" ;
2023-04-24 16:30:40 -05:00
import { NewCollection } from "@/types/global" ;
2023-02-18 21:32:02 -06:00
2023-03-22 18:11:54 -05:00
type CollectionStore = {
2023-02-18 21:32:02 -06:00
collections : Collection [ ] ;
setCollections : ( ) = > void ;
2023-04-24 16:30:40 -05:00
addCollection : ( body : NewCollection ) = > Promise < boolean > ;
2023-02-18 21:32:02 -06:00
updateCollection : ( collection : Collection ) = > void ;
removeCollection : ( collectionId : number ) = > void ;
} ;
2023-03-22 18:11:54 -05:00
const useCollectionStore = create < CollectionStore > ( ) ( ( set ) = > ( {
2023-02-18 21:32:02 -06:00
collections : [ ] ,
setCollections : async ( ) = > {
const response = await fetch ( "/api/routes/collections" ) ;
const data = await response . json ( ) ;
if ( response . ok ) set ( { collections : data.response } ) ;
} ,
2023-04-24 16:30:40 -05:00
addCollection : async ( body ) = > {
2023-02-18 21:32:02 -06:00
const response = await fetch ( "/api/routes/collections" , {
2023-04-24 16:30:40 -05:00
body : JSON.stringify ( body ) ,
2023-02-18 21:32:02 -06:00
headers : {
"Content-Type" : "application/json" ,
} ,
method : "POST" ,
} ) ;
const data = await response . json ( ) ;
2023-04-25 07:39:46 -05:00
console . log ( data ) ;
2023-02-18 21:32:02 -06:00
if ( response . ok )
set ( ( state ) = > ( {
collections : [ . . . state . collections , data . response ] ,
} ) ) ;
2023-04-24 16:30:40 -05:00
return response . ok ;
2023-02-18 21:32:02 -06:00
} ,
updateCollection : ( collection ) = >
set ( ( state ) = > ( {
collections : state.collections.map ( ( c ) = >
c . id === collection . id ? collection : c
) ,
} ) ) ,
removeCollection : ( collectionId ) = > {
set ( ( state ) = > ( {
collections : state.collections.filter ( ( c ) = > c . id !== collectionId ) ,
} ) ) ;
} ,
} ) ) ;
2023-03-22 18:11:54 -05:00
export default useCollectionStore ;