From f87f6c249535453b8bd3718dc7cdc84dcbbdbe13 Mon Sep 17 00:00:00 2001
From: John Estabrook <jestabro@vyos.io>
Date: Thu, 5 Aug 2021 11:24:47 -0500
Subject: http-api: T2768: example using GraphQL for high-level config
 operations

(cherry picked from commit b168b4cc7da456f14714d917cdc7a1c6b8df9af5)
---
 src/services/api/graphql/recipes/recipe.py | 49 ++++++++++++++++++++++++++++++
 1 file changed, 49 insertions(+)
 create mode 100644 src/services/api/graphql/recipes/recipe.py

(limited to 'src/services/api/graphql/recipes/recipe.py')

diff --git a/src/services/api/graphql/recipes/recipe.py b/src/services/api/graphql/recipes/recipe.py
new file mode 100644
index 000000000..8fbb9e0bf
--- /dev/null
+++ b/src/services/api/graphql/recipes/recipe.py
@@ -0,0 +1,49 @@
+from ariadne import convert_camel_case_to_snake
+import vyos.defaults
+from vyos.template import render
+
+class Recipe(object):
+    def __init__(self, session, data):
+        self._session = session
+        self.data = data
+        self._name = convert_camel_case_to_snake(type(self).__name__)
+
+    @property
+    def data(self):
+        return self.__data
+
+    @data.setter
+    def data(self, data):
+        if isinstance(data, dict):
+            self.__data = data
+        else:
+            raise ValueError("data must be of type dict")
+
+    def configure(self):
+        session = self._session
+        data = self.data
+        func_base_name = self._name
+
+        tmpl_file = f'{func_base_name}.tmpl'
+        cmd_file = f'/tmp/{func_base_name}.cmds'
+        tmpl_dir = vyos.defaults.directories['api_templates']
+
+        try:
+            render(cmd_file, tmpl_file, data, location=tmpl_dir)
+            commands = []
+            with open(cmd_file) as f:
+                lines = f.readlines()
+            for line in lines:
+                commands.append(line.split())
+            for cmd in commands:
+                if cmd[0] == 'set':
+                    session.set(cmd[1:])
+                elif cmd[0] == 'delete':
+                    session.delete(cmd[1:])
+                else:
+                    raise ValueError('Operation must be "set" or "delete"')
+            session.commit()
+        except Exception as error:
+            raise error
+
+
-- 
cgit v1.2.3