| 24 | # CREATE new node |
| 25 | @router.post('/create_node', response_model=Node) |
| 26 | async def create_node(label: str, node_attributes: dict, |
| 27 | current_user: User = Depends(get_current_active_user)): |
| 28 | # Check that node is not User |
| 29 | if label == 'User': |
| 30 | raise HTTPException( |
| 31 | status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, |
| 32 | detail="Operation not permitted, cannot create a User with this method.", |
| 33 | headers={"WWW-Authenticate": "Bearer"}) |
| 34 | |
| 35 | # Check that node has an acceptable label |
| 36 | if label not in node_labels: |
| 37 | raise HTTPException( |
| 38 | status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, |
| 39 | detail="Operation not permitted, node label is not accepted.", |
| 40 | headers={"WWW-Authenticate": "Bearer"}) |
| 41 | |
| 42 | # Check that attributes dictionary does not modify base fields |
| 43 | for key in node_attributes: |
| 44 | if key in base_properties: |
| 45 | raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, |
| 46 | detail="Operation not permitted, you cannot modify those fields with this method.", |
| 47 | headers={"WWW-Authenticate": "Bearer"}) |
| 48 | |
| 49 | unpacked_attributes = 'SET ' + ', '.join(f'new_node.{key}=\'{value}\'' for (key, value) in node_attributes.items()) |
| 50 | |
| 51 | cypher = f""" |
| 52 | CREATE (new_node:{label})\n' |
| 53 | SET new_node.created_by = $created_by\n' |
| 54 | SET new_node.created_time = $created_time\n' |
| 55 | {unpacked_attributes}\n |
| 56 | RETURN new_node, LABELS(new_node) as labels, ID(new_node) as id') |
| 57 | """ |
| 58 | |
| 59 | with neo4j_driver.session() as session: |
| 60 | result = session.run( |
| 61 | query=cypher, |
| 62 | parameters={ |
| 63 | 'created_by': current_user.username, |
| 64 | 'created_time': str(datetime.now(timezone.utc)), |
| 65 | 'attributes': node_attributes, |
| 66 | }, |
| 67 | ) |
| 68 | |
| 69 | node_data = result.data()[0] |
| 70 | |
| 71 | return Node(node_id=node_data['id'], |
| 72 | labels=node_data['labels'], |
| 73 | properties=node_data['new_node']) |
| 74 | |
| 75 | |
| 76 | # READ data about a node in the graph by ID |