balena-sdk
Version:
The Balena JavaScript SDK
109 lines (105 loc) • 4.03 kB
JavaScript
;
/*
Copyright 2017 Balena
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildDependentResource = buildDependentResource;
/*
This file contains an abstract implementation for dependent metadata resources:
key-value resources directly attached to a parent (e.g. tags, config variables).
*/
const util_1 = require("../util");
function buildDependentResource({ pine }, { resourceName, resourceKeyField, parentResourceName, getResourceId, }) {
const exports = {
getAll(options) {
return pine.get({
resource: resourceName,
options: (0, util_1.mergePineOptions)({
$orderby: {
[resourceKeyField]: 'asc',
},
}, options),
});
},
async getAllByParent(parentParam, options) {
const id = await getResourceId(parentParam);
return await exports.getAll((0, util_1.mergePineOptions)({
$filter: { [parentResourceName]: id },
$orderby: {
[resourceKeyField]: 'asc',
},
}, options));
},
async get(parentParam, key) {
const id = await getResourceId(parentParam);
const [result] = await pine.get({
resource: resourceName,
options: {
$select: 'value',
$filter: {
[parentResourceName]: id,
[resourceKeyField]: key,
},
},
});
if (result) {
return result.value;
}
},
async set(parentParam, key, value) {
value = String(value);
// Trying to avoid an extra HTTP request
// when the provided parameter looks like an id.
// Note that this throws an exception for missing names/uuids,
// but not for missing ids
const parentId = (0, util_1.isId)(parentParam)
? parentParam
: await getResourceId(parentParam);
try {
await pine.upsert({
resource: resourceName,
id: {
[parentResourceName]: parentId,
[resourceKeyField]: key,
},
body: {
value,
},
});
}
catch (err) {
// Since Pine 7, when the post throws a 401
// then the associated parent resource might not exist.
// If we never checked that the resource actually exists
// then we should reject an appropriate error.
if (!(0, util_1.isUnauthorizedResponse)(err) || !(0, util_1.isId)(parentParam)) {
throw err;
}
await getResourceId(parentParam);
throw err;
}
},
async remove(parentParam, key) {
const parentId = await getResourceId(parentParam);
await pine.delete({
resource: resourceName,
options: {
$filter: {
[parentResourceName]: parentId,
[resourceKeyField]: key,
},
},
});
},
};
return exports;
}