(req, res, next)
| 39 | |
| 40 | // Handles a PATCH request |
| 41 | async function patchHandler (req, res, next) { |
| 42 | debug(`PATCH -- ${req.originalUrl}`) |
| 43 | try { |
| 44 | // Obtain details of the target resource |
| 45 | const ldp = req.app.locals.ldp |
| 46 | let path, contentType |
| 47 | let resourceExists = true |
| 48 | try { |
| 49 | // First check if the file already exists |
| 50 | ({ path, contentType } = await ldp.resourceMapper.mapUrlToFile({ url: req })) |
| 51 | } catch (err) { |
| 52 | // debug('PATCH -- File does not exist, creating new resource. Error:', err.message) |
| 53 | // If the file doesn't exist, request to create one with the file media type as contentType |
| 54 | ({ path, contentType } = await ldp.resourceMapper.mapUrlToFile( |
| 55 | { url: req, createIfNotExists: true, contentType: contentTypeForNew(req) })) |
| 56 | // check if a folder with same name exists |
| 57 | try { |
| 58 | await ldp.checkItemName(req) |
| 59 | } catch (err) { |
| 60 | return next(err) |
| 61 | } |
| 62 | resourceExists = false |
| 63 | } |
| 64 | const { url } = await ldp.resourceMapper.mapFileToUrl({ path, hostname: req.hostname }) |
| 65 | const resource = { path, contentType, url } |
| 66 | debug('PATCH -- Target <%s> (%s)', url, contentType) |
| 67 | |
| 68 | // Obtain details of the patch document |
| 69 | const patch = {} |
| 70 | patch.text = req.body ? req.body.toString() : '' |
| 71 | patch.uri = `${url}#patch-${hash(patch.text)}` |
| 72 | patch.contentType = getContentType(req.headers) |
| 73 | if (!patch.contentType) { |
| 74 | throw error(400, 'PATCH request requires a content-type via the Content-Type header') |
| 75 | } |
| 76 | debug('PATCH -- Received patch (%d bytes, %s)', patch.text.length, patch.contentType) |
| 77 | const parsePatch = PATCH_PARSERS[patch.contentType] |
| 78 | if (!parsePatch) { |
| 79 | throw error(415, `Unsupported patch content type: ${patch.contentType}`) |
| 80 | } |
| 81 | res.header('Accept-Patch', patch.contentType) // is this needed ? |
| 82 | // Parse the patch document and verify permissions |
| 83 | const patchObject = await parsePatch(url, patch.uri, patch.text) |
| 84 | await checkPermission(req, patchObject, resourceExists) |
| 85 | |
| 86 | // Create the enclosing directory, if necessary |
| 87 | await ldp.createDirectory(path, req.hostname) |
| 88 | |
| 89 | // Patch the graph and write it back to the file |
| 90 | const result = await withLock(path, async () => { |
| 91 | const graph = await readGraph(resource) |
| 92 | await applyPatch(patchObject, graph, url) |
| 93 | return writeGraph(graph, resource, ldp.resourceMapper.resolveFilePath(req.hostname), ldp.serverUri) |
| 94 | }) |
| 95 | // Send the status and result to the client |
| 96 | res.status(resourceExists ? 200 : 201) |
| 97 | res.send(result) |
| 98 | } catch (err) { |
no test coverage detected