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-03-28 10:11:34 -05:00
import { prisma } from "@/lib/api/db" ;
import { ExtendedLink } from "@/types/global" ;
2023-05-01 05:07:01 -05:00
import { UsersAndCollections } from "@prisma/client" ;
2023-04-26 15:40:48 -05:00
import getPermission from "@/lib/api/getPermission" ;
2023-03-28 10:11:34 -05:00
export default async function ( link : ExtendedLink , userId : number ) {
if ( ! link ) return { response : "Please choose a valid link." , status : 401 } ;
2023-04-26 15:40:48 -05:00
const collectionIsAccessible = await getPermission ( userId , link . collectionId ) ;
2023-03-28 10:11:34 -05:00
const memberHasAccess = collectionIsAccessible ? . members . some (
( e : UsersAndCollections ) = > e . userId === userId && e . canUpdate
) ;
2023-05-01 05:07:01 -05:00
if ( link . collection . ownerId ) {
const collectionIsAccessible = await getPermission (
userId ,
link . collection . id
) ;
2023-03-28 10:11:34 -05:00
2023-05-01 05:07:01 -05:00
const memberHasAccess = collectionIsAccessible ? . members . some (
( e : UsersAndCollections ) = > e . userId === userId && e . canCreate
) ;
if ( ! ( collectionIsAccessible ? . ownerId === userId || memberHasAccess ) )
return { response : "Collection is not accessible." , status : 401 } ;
} else {
link . collection . ownerId = userId ;
}
const updatedLink : ExtendedLink = await prisma . link . update ( {
2023-03-28 10:11:34 -05:00
where : {
id : link.id ,
} ,
data : {
name : link.name ,
collection : {
connectOrCreate : {
where : {
name_ownerId : {
ownerId : link.collection.ownerId ,
name : link.collection.name ,
} ,
} ,
create : {
name : link.collection.name ,
ownerId : userId ,
} ,
} ,
} ,
tags : {
2023-03-28 10:37:36 -05:00
set : [ ] ,
2023-03-28 10:11:34 -05:00
connectOrCreate : link.tags.map ( ( tag ) = > ( {
where : {
name_ownerId : {
name : tag.name ,
ownerId : link.collection.ownerId ,
} ,
} ,
create : {
name : tag.name ,
owner : {
connect : {
id : link.collection.ownerId ,
} ,
} ,
} ,
} ) ) ,
} ,
} ,
2023-05-01 05:07:01 -05:00
include : {
tags : true ,
collection : true ,
} ,
2023-03-28 10:11:34 -05:00
} ) ;
return { response : updatedLink , status : 200 } ;
}