Skip to content

Commit

Permalink
enable to add an element with ordinal
Browse files Browse the repository at this point in the history
with a safer way to assign ordinal, not relying on loop (which is based on
array length) but on existing ordinal, to better handle legacy element
without ordinal
  • Loading branch information
jum-s committed Apr 22, 2024
1 parent 4704e9a commit 92aad55
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 19 deletions.
13 changes: 10 additions & 3 deletions server/controllers/listings/lib/elements.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { map } from 'lodash-es'
import { map, maxBy } from 'lodash-es'
import dbFactory from '#db/couchdb/base'
import { isNonEmptyArray } from '#lib/boolean_validations'
import { newError } from '#lib/error/error'
Expand Down Expand Up @@ -41,12 +41,12 @@ export async function createListingElements ({ listing, uris, userId }) {
if (listing.creator !== userId) {
throw newError('wrong user', 403, { userId, listingId })
}
let currentOrdinal = 0
const elements = uris.map(uri => {
const ordinal = highestOrdinal(listing.elements) + 1
return createElementDoc({
list: listingId,
uri,
ordinal: currentOrdinal++,
ordinal,
})
})
const res = await db.bulk(elements)
Expand All @@ -61,3 +61,10 @@ export async function bulkUpdateElements ({ oldElements, attribute, value }) {
}

const elementsBulkUpdate = db.bulk

function highestOrdinal (elements: ListingElement[]) {
if (elements.length === 0) return -1

const highestOrdinalElement = maxBy(elements, 'ordinal')
return highestOrdinalElement.ordinal
}
21 changes: 5 additions & 16 deletions tests/api/listings/ordinal.test.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,9 @@
import { createEdition } from '../fixtures/entities.js'
import { createListing } from '../fixtures/listings.js'
import { authReq } from '../utils/utils.js'

const endpoint = '/api/lists?action='
const byIds = `${endpoint}by-ids&with-elements=true`
import { createListingWithElements } from '../fixtures/listings.js'

describe('element:listing-ordinal', () => {
it('should add elements with ordinals', async () => {
const { listing } = await createListing()
const { uri } = await createEdition()
await authReq('post', `${endpoint}add-elements`, {
id: listing._id,
uris: [ uri ],
})
const res = await authReq('get', `${byIds}&ids=${listing._id}`)
const firstListing = res.lists[listing._id]
firstListing.elements[0].ordinal.should.equal(0)
it('should create elements with a listingId', async () => {
const { listing } = await createListingWithElements()
listing.elements[0].ordinal.should.equal(0)
listing.elements[1].ordinal.should.equal(1)
})
})

0 comments on commit 92aad55

Please sign in to comment.