Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

POST /collections endpoint to create collection #295

Merged
merged 6 commits into from
Oct 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
### Added

- Added pre-hook and post-hook Lambda examples
- POST /collections endpoint to create collections

### Changed

Expand Down
21 changes: 21 additions & 0 deletions src/lambdas/api/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,27 @@ app.get('/collections', async (req, res, next) => {
}
})

app.post('/collections', async (req, res, next) => {
if (txnEnabled) {
const collectionId = req.body.collection
try {
await api.createCollection(req.body, es)
res.location(`${req.endpoint}/collections/${collectionId}`)
res.sendStatus(201)
} catch (error) {
if (error instanceof Error
&& error.name === 'ResponseError'
&& error.message.includes('version_conflict_engine_exception')) {
res.sendStatus(409)
} else {
next(error)
}
}
} else {
next(createError(404))
}
})

app.get('/collections/:collectionId', async (req, res, next) => {
const { collectionId } = req.params
try {
Expand Down
19 changes: 18 additions & 1 deletion src/lib/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,13 @@ const parsePath = function (inpath) {
// Impure - mutates results
const addCollectionLinks = function (results, endpoint) {
results.forEach((result) => {
const { id, links } = result
const { id } = result
let { links } = result
if (links == null) {
links = []
result.links = links
}

// self link
links.splice(0, 0, {
rel: 'self',
Expand Down Expand Up @@ -639,6 +645,16 @@ const getCollection = async function (collectionId, backend, endpoint = '') {
return new Error('Collection retrieval failed')
}

const createCollection = async function (collection, backend) {
const response = await backend.indexCollection(collection)
logger.debug(`Create Collection: ${JSON.stringify(response)}`)

if (response) {
return response
}
return new Error(`Error creating collection ${collection}`)
}

const getItem = async function (collectionId, itemId, backend, endpoint = '') {
const itemQuery = { collections: [collectionId], id: itemId }
const { results } = await backend.search(itemQuery)
Expand Down Expand Up @@ -694,6 +710,7 @@ module.exports = {
getCatalog,
getCollections,
getCollection,
createCollection,
getItem,
searchItems,
parsePath,
Expand Down
27 changes: 26 additions & 1 deletion src/lib/es.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,30 @@ function buildFieldsFilter(parameters) {
return { _sourceIncludes, _sourceExcludes }
}

/*
* Create a new Collection
*
*/
async function indexCollection(collection) {
const client = await esClient.client()

const exists = await client.indices.exists({ index: COLLECTIONS_INDEX })
if (!exists.body) {
await esClient.createIndex(COLLECTIONS_INDEX)
}

await client.index({
index: COLLECTIONS_INDEX,
id: collection.id,
body: collection,
opType: 'create'
})

const response = await esClient.createIndex(collection.id)

return response
}

/*
* Create a new Item in an index corresponding to the Collection
*
Expand Down Expand Up @@ -429,8 +453,9 @@ async function updateItem(item) {
}

module.exports = {
getCollection,
getCollections,
getCollection,
indexCollection,
getItem,
getItemCreated,
indexItem,
Expand Down
37 changes: 37 additions & 0 deletions tests/system/test-api-collection-post.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const test = require('ava')
const { deleteAllIndices } = require('../helpers/es')
const { randomId } = require('../helpers/utils')
const systemTests = require('../helpers/system-tests')

test.before(async (t) => {
await deleteAllIndices()

t.context = await systemTests.setup()
})

test.after.always(async (t) => {
if (t.context.api) await t.context.api.close()
})

test('POST /collections creates a collection', async (t) => {
const collectionId = randomId('collection')

const response = await t.context.api.client.post('collections',
{ json: { id: collectionId }, resolveBodyOnly: false, responseType: 'text' })

t.is(response.statusCode, 201)
t.is(response.headers['content-type'], 'text/plain; charset=utf-8')
t.is(response.body, 'Created')

// ES needs a second to process the create request
// eslint-disable-next-line no-promise-executor-return
await new Promise((r) => setTimeout(r, 1000))

const response2 = await t.context.api.client.get(`collections/${collectionId}`,
{ resolveBodyOnly: false })

t.is(response2.statusCode, 200)
t.is(response2.headers['content-type'], 'application/json; charset=utf-8')
// @ts-expect-error We need to validate these responses
t.is(response2.body.id, collectionId)
})
2 changes: 1 addition & 1 deletion tests/system/test-api-item-post.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ test('POST /collections/:collectionId/items', async (t) => {
t.assert(response.headers['location'].endsWith(`/collections/${collectionId}/items/${itemId}`))
t.is(response.body, 'Created')

// ES needs a second to process the patch request
// ES needs a second to process the create request
// eslint-disable-next-line no-promise-executor-return
await new Promise((r) => setTimeout(r, 1000))

Expand Down