Allow owner to remove nodes

This commit is contained in:
Andrea Maria Piana 2019-03-20 10:16:40 +01:00
parent 7966cda2bb
commit 4358ad5c2c
No known key found for this signature in database
GPG Key ID: AA6CCA6DE0E06424
3 changed files with 59 additions and 4 deletions

View File

@ -4,7 +4,7 @@ contract Nodes
{
address owner;
string[] public nodes;
uint public nodeCount;
mapping(string => uint) nodeIndex;
modifier onlyOwner() {
require(msg.sender == owner);
@ -17,12 +17,29 @@ contract Nodes
owner = msg.sender;
}
function nodeCount()
view
public
returns
(uint)
{
return nodes.length;
}
function addNode(string memory _node)
public
onlyOwner
{
nodeIndex[_node] = nodes.length;
nodes.push(_node);
nodeCount++;
}
function deleteNode(string memory _node)
public
onlyOwner
{
uint index = nodeIndex[_node];
_deleteNode(index);
}
function deleteAll()
@ -30,7 +47,13 @@ contract Nodes
onlyOwner
{
delete nodes;
nodeCount = 0;
}
function _deleteNode(uint index) internal {
require(index < nodes.length);
nodes[index] = nodes[nodes.length-1];
delete nodes[nodes.length-1];
nodes.length--;
}
function () external payable {

View File

@ -18,7 +18,9 @@
"scripts": {
"test": "truffle test",
"lint": "eslint . --ext .js",
"lint-watch": "nodemon --exec 'npm run lint'",
"lint-watch": "nodemon --exec 'npm run lint' -e js,sol",
"test-watch": "nodemon --exec 'npm test' -e js,sol",
"watch": "nodemon --exec 'npm test && npm run lint' -e js,sol",
"validate": "npm test && npm run lint"
},
"author": "",

View File

@ -45,6 +45,36 @@ contract('Nodes', async (accounts) => {
});
});
describe('deleteNode', async () => {
describe('called by the owner', async () => {
beforeEach(async () => {
await instance.addNode(node1);
await instance.addNode(node2);
await instance.deleteNode(node1);
});
it('removes the first node', async () => {
const actualNode2 = await instance.nodes(0);
assert.equal(actualNode2, node2);
});
it('sets the count', async () => {
const actualNodeCount = await instance.nodeCount();
assert.equal(1, actualNodeCount);
});
});
describe('called by someone else', async () => {
it('throws an exception', async () => {
try {
await instance.deleteNode(node1, { from: accounts[1] });
} catch (error) {
return;
}
assert.fail('it should throw an exception');
});
});
});
describe('deleteAll', async () => {
beforeEach(async () => {
await instance.addNode(node1);