lumic-backend-functions
v1.0.88
Published
A repository of executable mjs functions that execute Apollo GraphQL queries or mutations and parse the props input to align with the required variables object for a content model in the backend.
Downloads
22
Readme
Lumic Backend Functions
Description
The lumicBackendFunctions
repository is a dynamic backend solution designed to support Lumic.ai by providing a comprehensive set of serverless functions for various content models. Built with a focus on scalability and efficiency, this repository facilitates seamless GraphQL operations, allowing for efficient data querying and mutation. The functions are continuously updated to reflect changes in content models, ensuring that the backend remains robust and adaptable to evolving requirements.
This repository encompasses a wide range of functionalities, including user account management, workflow automation, action handling, and documentation management. It is ideal for applications that require a reliable and flexible backend infrastructure to manage user interactions and processes effectively.
Features
The lumicBackendFunctions
repository offers a robust set of features designed to enhance user and process management within web applications. Here’s a breakdown of its key features and benefits:
- User Authentication: Securely manage user accounts with registration, login, and account updates.
- Account Management: Comprehensive functions for creating, updating, and deleting user accounts.
- Workflow Automation: Create and manage workflows that automate processes, improving efficiency and reducing manual effort.
- GraphQL Integration: Leverage GraphQL for efficient data querying and mutation, allowing for flexible and powerful interactions with the database.
- Action Management: Create, update, and delete actions associated with workflows, enabling dynamic process management.
- Documentation Management: Maintain documentation related to workflows and actions, ensuring clarity and ease of use for developers.
- Error Handling: Built-in error handling for robust application performance and user experience.
Environment Setup
Ensure you have Node.js and NPM installed on your machine.
Clone the repository to your local machine:
git clone https://github.com/Lumic-ai/lumicBackendFunctions.git
Navigate to the project directory:
cd lumicBackendFunctions
Installation
Follow these steps to install the necessary dependencies and set up your environment:
Install NPM Dependencies: Run the following command to install all required NPM packages:
npm install
Set Up Environment Variables: Create a
.env
file in the root of your project and add the required environment variables:AUTH_SECRET=your_auth_secret SESSION_TIMEOUT=your_session_timeout DATABASE_URL=your_database_url GRAPHQL_ENDPOINT=your_graphql_endpoint
By completing these steps, you will have the lumicBackendFunctions
repository set up and ready for use in your application.
File Tree Structure
[...file tree omitted for brevity...]
Usage
Input Parameters
For
createOneUser
:username
(String): The desired username for the new user.email
(String): The email address of the new user.password
(String): The password for the new user account.
For
getWorkflow
:workflowId
(String): The unique identifier of the workflow to retrieve.
For
updateOneAccount
:accountId
(String): The unique identifier of the account to update.newDetails
(Object): An object containing the new account details (e.g.,email
,username
).
Expected Output
- For
createOneUser
: Returns a response object containing user details and a success message. - For
getWorkflow
: Returns the workflow object with all associated details. - For
updateOneAccount
: Returns a confirmation message indicating the account has been updated successfully.
Test Data
User Creation:
{ "username": "testuser", "email": "[email protected]", "password": "securePassword123" }
Workflow Retrieval:
{ "workflowId": "workflow-12345" }
Account Update:
{ "accountId": "12345", "newDetails": { "email": "[email protected]", "username": "newusername" } }
Code Examples
AWS Lambda Function Example
import pkg from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { HttpLink } from '@apollo/client/link/http';
import jwt from 'jsonwebtoken';
import { createOneDocumentation } from 'lumic-backend-functions';
const { ApolloClient, InMemoryCache } = pkg;
// Your JWT secret and salt
const jwtSecret = process.env.JWT_SECRET || 'yourJwtSecret';
const jwtSalt = process.env.JWT_SALT || 'yourJwtSalt';
// Function to generate a JWT token using the secret and salt
const generateJwtToken = (secret, salt) => {
return jwt.sign({ salt }, secret, { expiresIn: '1h' });
};
// Generate the JWT token
const token = generateJwtToken(jwtSecret, jwtSalt);
// HTTP Link to the GraphQL endpoint
const httpLink = new HttpLink({
uri: process.env.GRAPHQL_ENDPOINT || 'https://your-graphql-endpoint.com',
});
// Set the authorization context with the JWT token
const authLink = setContext(async (_, { headers }) => {
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
};
});
// Initialize the Apollo Client
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
// Example of using the client within a Lambda function
export const handler = async (event) => {
try {
// Assuming `event` contains the necessary properties to create documentation
const documentationData = {
title: event.title,
summary: event.summary,
content: event.content,
tagId: event.tagId,
dependency: event.dependency,
subsections: event.subsections,
examples: event.examples,
tags: event.tags,
useCases: event.useCases
};
// Use the createOneDocumentation function with the Apollo Client instance
const result = await createOneDocumentation(documentationData, client);
return {
statusCode: 200,
body: JSON.stringify(result),
};
} catch (error) {
console.error('Error:', error);
return {
statusCode: 500,
body: JSON.stringify({ error: 'An error occurred' }),
};
}
};
Server-Side Next.js Component Example
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import jwt from 'jsonwebtoken';
import { createOneDocumentation } from 'lumic-backend-functions';
// Your JWT secret and salt
const jwtSecret = process.env.JWT_SECRET || 'yourJwtSecret';
const jwtSalt = process.env.JWT_SALT || 'yourJwtSalt';
// Function to generate a JWT token using the secret and salt
const generateJwtToken = (secret, salt) => {
return jwt.sign({ salt }, secret, { expiresIn: '1h' });
};
// Generate the JWT token
const token = generateJwtToken(jwtSecret, jwtSalt);
const httpLink = new HttpLink({
uri: process.env.GRAPHQL_ENDPOINT || 'https://your-graphql-endpoint.com',
});
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
};
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
export async function getServerSideProps(context) {
const documentationData = {
title: "Example Title",
summary: "Example Summary",
content: "Example Content",
tagId: "tag-id",
// Add more fields as needed
};
const result = await createOneDocumentation(documentationData, client);
return {
props: {
documentation: result,
},
};
}
export default function DocumentationPage({ documentation }) {
return (
<div>
<h1>{documentation.title}</h1>
<p>{documentation.summary}</p>
<div>{documentation.content}</div>
</div>
);
}
Client-Side Next.js Component Example
import { useState } from 'react';
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import jwt from 'jsonwebtoken';
import { createOneDocumentation } from 'lumic-backend-functions';
// Your JWT secret and salt
const jwtSecret = process.env.NEXT_PUBLIC_JWT_SECRET || 'yourJwtSecret';
const jwtSalt = process.env.NEXT_PUBLIC_JWT_SALT || 'yourJwtSalt';
// Function to generate a JWT token using the secret and salt
const generateJwtToken = (secret, salt) => {
return jwt.sign({ salt }, secret, { expiresIn: '1h' });
};
// Generate the JWT token
const token = generateJwtToken(jwtSecret, jwtSalt);
const httpLink = new HttpLink({
uri: process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT || 'https://your-graphql-endpoint.com',
});
const authLink = setContext((_, { headers }) =>
{
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
};
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
export default function DocumentationForm() {
const [formData, setFormData] = useState({
title: '',
summary: '',
content: '',
tagId: '',
// Add more fields as needed
});
const handleSubmit = async (e) => {
e.preventDefault();
try {
const result = await createOneDocumentation(formData, client);
console.log('Documentation created:', result);
} catch (error) {
console.error('Error creating documentation:', error);
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="title"
value={formData.title}
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
placeholder="Title"
/>
<textarea
name="summary"
value={formData.summary}
onChange={(e) => setFormData({ ...formData, summary: e.target.value })}
placeholder="Summary"
/>
<textarea
name="content"
value={formData.content}
onChange={(e) => setFormData({ ...formData, content: e.target.value })}
placeholder="Content"
/>
<input
type="text"
name="tagId"
value={formData.tagId}
onChange={(e) => setFormData({ ...formData, tagId: e.target.value })}
placeholder="Tag ID"
/>
{/* Add more fields as needed */}
<button type="submit">Create Documentation</button>
</form>
);
}
Contributing
We welcome contributions to this repository! To contribute, please follow these guidelines:
- Fork the repository: Create your own copy of the repository by forking it.
- Create a new branch: Use a descriptive name for your branch (e.g.,
feature/new-feature
). - Make your changes: Implement your feature or fix a bug.
- Write tests: Ensure that your changes are covered by tests.
- Submit a pull request: Once your changes are ready, submit a pull request to the
main
branch of the original repository.
Please ensure that your code adheres to the existing style and includes appropriate documentation.
License
This repository is licensed under the MIT License. See the LICENSE file for more details.
Acknowledgements
We would like to thank all contributors and users of this repository for their support and feedback.
This project is a product of Lumic.ai.
Thanks for reading this far! Why did the developer go broke? Because he used up all his cache!