@@ -5,6 +5,7 @@ import { ICapabilities, IHashSettings, IResource } from '../interfaces/Resource'
55import Logger from '../Logger'
66import {
77 AuthenticationError ,
8+ UnknownFolderUpdateError ,
89 CancelledSyncError , HttpError , MissingPermissionsError ,
910 NetworkError , ParseResponseError ,
1011 RedirectError ,
@@ -240,13 +241,39 @@ export default class LinkwardenAdapter implements Adapter, IResource<typeof Item
240241 const { response : collections } = await this . sendRequest ( 'GET' , `/api/v1/collections` )
241242
242243 let rootCollection = collections . find ( collection => collection . name === this . server . serverFolder && collection . parentId == null )
244+
243245 if ( ! rootCollection ) {
244- ( { response : rootCollection } = await this . sendRequest (
245- 'POST' , '/api/v1/collections' ,
246- 'application/json' ,
247- {
248- name : this . server . serverFolder ,
249- } ) )
246+ const segments = this . server . serverFolder . split ( '/' ) . filter ( seg => seg . length > 0 )
247+
248+ if ( segments . length === 0 ) {
249+ throw new UnknownFolderUpdateError ( )
250+ }
251+ let currentParentId = null
252+ let current = null
253+
254+ for ( const segment of segments ) {
255+ const expectedParent = currentParentId == null ? null : String ( currentParentId )
256+ current = collections . find ( collection => {
257+ const actualParent = collection . parentId == null ? null : String ( collection . parentId )
258+ return collection . name === segment && actualParent === expectedParent
259+ } )
260+ if ( ! current ) {
261+ const body : { name : string ; parentId ?: string | number } = { name : segment }
262+ if ( currentParentId != null ) {
263+ body . parentId = currentParentId
264+ }
265+ ( { response : current } = await this . sendRequest (
266+ 'POST' , '/api/v1/collections' ,
267+ 'application/json' ,
268+ body
269+ ) )
270+ collections . push ( current )
271+ }
272+ currentParentId = current . id
273+ }
274+ if ( current ) {
275+ rootCollection = current
276+ }
250277 }
251278
252279 const buildTree = ( collection , isRoot = false ) => {
0 commit comments