This repository has been archived by the owner on Aug 25, 2023. It is now read-only.
/
writeBlobHandler.ts
40 lines (36 loc) · 2.04 KB
/
writeBlobHandler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { WacLdpTask, TaskType } from '../api/http/HttpParser'
import { WacLdpResponse, ErrorResult, ResultType } from '../api/http/HttpResponder'
import Debug from 'debug'
import { getResourceDataAndCheckETag } from './getResourceDataAndCheckETag'
import { makeResourceData, objectToStream } from '../rdf/ResourceDataUtils'
import { StoreManager } from '../rdf/StoreManager'
import { ACL } from '../rdf/rdf-constants'
const debug = Debug('write-blob-handler')
export const writeBlobHandler = {
canHandle: (wacLdpTask: WacLdpTask) => (wacLdpTask.wacLdpTaskType() === TaskType.blobWrite),
requiredAccessModes: [ ACL.Write ],
handle: async function (task: WacLdpTask, storeManager: StoreManager, aud: string, skipWac: boolean, appendOnly: boolean): Promise<WacLdpResponse> {
const resourceDataBefore = await getResourceDataAndCheckETag(task, storeManager)
const blobExists: boolean = !!resourceDataBefore
debug('operation writeBlob!', blobExists)
// see https://github.com/inrupt/wac-ldp/issues/61
// and https://github.com/inrupt/wac-ldp/issues/60
const ifMatchHeaderPresent = task.ifMatch() || task.ifNoneMatchStar()
debug('checking If-Match presence', ifMatchHeaderPresent, task.ifMatch(), task.ifNoneMatchStar(), task.ifMatchRequired, blobExists)
if (blobExists || (task.ifMatchRequired && !ifMatchHeaderPresent)) {
debug('attempt to overwrite existing resource')
throw new ErrorResult(ResultType.PreconditionRequired)
}
const resultType = (blobExists ? ResultType.OkayWithoutBody : ResultType.Created)
const contentType: string | undefined = task.contentType()
debug('contentType', contentType)
const resourceData = makeResourceData(contentType ? contentType : '', await task.requestBody())
await storeManager.setRepresentation(task.fullUrl(), objectToStream(resourceData))
debug('write blob handler changed a resource', task.fullUrl())
return {
resultType,
createdLocation: (blobExists ? undefined : task.fullUrl()),
resourcesChanged: [ task.fullUrl() ]
} as WacLdpResponse
}
}