Skip to content

Commit

Permalink
feat: implement custom handlers for monikers
Browse files Browse the repository at this point in the history
  • Loading branch information
mfrankruijter committed Nov 8, 2022
1 parent 93e8080 commit 3630a76
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 9 deletions.
64 changes: 64 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,49 @@ In the following example the contents of the endpoint are being written to
}
```

### customInputs
Custom inputs can be created to import information from for example an API.
These custom inputs can return multiple inputs to the main script.
A custom input can be configured as follows, in the monikers.json file add an
additional node to the main configuration with the name `customInputs`:
```json
{
"customInputs": {
"my-custom-type": {
"type": "mycustomtype",
"config": {...myconfig}
}
}
}
```

The name of the first key `my-custom-type` will represent the prefix in the output.
The value of `type` will be the reference to the custom handler (up next). The `config`
node will be passed to the custom handler to pass for example API keys.

To create a custom handler, add a new class to the `lib/handlers/__init__.py` file:
```python
class MyCustomHandler():
def handle(self, customKey, config={}):
resultSet = {}
# Your custom logic here
return resultSet
```

The `resultSet` is expected to be a key-value(`string`) pair.
Then the custom handler can be registered in `moniker.py` by registering it by a key as
the second parameter of the Handler initiation:
```python
handler = Handler(
Config(configFile),
{
"mycustomtype": MyCustomHandler(),
}
)
```

Now the handler will be called in each iteration.

### fetchFrequency
The `fetchFrequency` can be configured to determine the polling rate of any URL
being called. Every increment is one second. So the default of `10` will result
Expand Down Expand Up @@ -107,6 +150,27 @@ The outputs can have an unlimited amount of entries.
}
```

It is also possible to conditionally give an alternative result as output when a field is empty.
This can be done by also adding the `onEmpty` configuration to the output entry.

```json
{
"outputs": {
"someoutput": {
"file": "example-files\\output-file.txt",
"text": "PulseBear has written {input-file} scripts today",
"onEmpty": {
"field": "input-file",
"result": "No scripts today!"
}
}
}
}
```

In the above example, the result in the output file will be `No scripts today!` when the field
`input-file` is empty.

## Running the script

To run the script in the foreground (seeing a terminal window), double click on
Expand Down
Empty file added lib/handlers/__init__.py
Empty file.
50 changes: 42 additions & 8 deletions lib/moniker_handler/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,35 @@ def __init__(self, configFile=None):
self.outputs = {}
self.fetchFrequency = 10
self.fetchInputs = {}
self.customInputs = {}

class Handler():
def __init__(self, config):
def __init__(self, config, customHandlers={}):
self.outputs = []
self.monikers = config.inputs
self.fetchFrequency = config.fetchFrequency
self.fetchInputs = config.fetchInputs
self.customInputs = config.customInputs
self.customHandlers = customHandlers

for outputFile in config.outputs:
self.outputs.append(
{
'file': config.outputs[outputFile]['file'],
'monikers': re.findall('{([A-z0-9_-]+)}', config.outputs[outputFile]['text']),
'text': config.outputs[outputFile]['text']
}
)
if 'onEmpty' in config.outputs[outputFile]:
self.outputs.append(
{
'file': config.outputs[outputFile]['file'],
'monikers': re.findall('{([A-z0-9_\\.-]+)}', config.outputs[outputFile]['text']),
'text': config.outputs[outputFile]['text'],
'onEmpty': config.outputs[outputFile]['onEmpty']
}
)
else:
self.outputs.append(
{
'file': config.outputs[outputFile]['file'],
'monikers': re.findall('{([A-z0-9_\\.-]+)}', config.outputs[outputFile]['text']),
'text': config.outputs[outputFile]['text']
}
)

def subscribe(self):
buffers = {}
Expand All @@ -46,6 +59,7 @@ def subscribe(self):
writeStream = io.open(self.monikers[endpoint], 'w+')
writeStream.write(webStream.read().decode('utf-8'))
writeStream.close()
webStream.close()
changedKeys = []
for moniker in buffers.keys():
buffers[moniker].seek(0)
Expand All @@ -55,8 +69,28 @@ def subscribe(self):
changedKeys.append(moniker)
content[moniker] = newContent

for customKey in self.customInputs:
customResult = self.customHandlers[self.customInputs[customKey]['type']].handle(customKey, self.customInputs[customKey]['config'])
for customFieldKey in customResult:
try:
if content[customFieldKey] != customResult:
changed = True
changedKeys.append(customFieldKey)
content[customFieldKey] = customResult[customFieldKey]
except:
changed = True
changedKeys.append(customFieldKey)
content[customFieldKey] = customResult[customFieldKey]

if changed:
for outputFile in self.outputs:
if 'onEmpty' in outputFile:
if content[outputFile['onEmpty']['field']] == '':
writeStream = io.open(outputFile['file'], 'w+')
writeStream.write(outputFile['onEmpty']['result'])
writeStream.close()
continue

for key in changedKeys:
if key in outputFile['monikers']:
outputText = outputFile['text']
Expand Down
7 changes: 6 additions & 1 deletion moniker.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,10 @@

configFile = os.path.join(os.path.dirname(__file__), "config/monikers.json")

handler = Handler(Config(configFile))
handler = Handler(
Config(configFile),
{
}
)

handler.subscribe()

0 comments on commit 3630a76

Please sign in to comment.