Skip to content

Commit

Permalink
Adding Object generation based on schema input.
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelandert committed Jul 31, 2024
1 parent 73dd063 commit fb38420
Show file tree
Hide file tree
Showing 4 changed files with 151 additions and 2 deletions.
1 change: 0 additions & 1 deletion apps/api/.wundergraph/operations/insertDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,6 @@ const metaSchema = {
function generateRandomObject() {
return {
$schema: metaSchema.$id,
$id: `https://alpha.ipfs.homin.io/UserSchema${Math.floor(Math.random() * 10000)}`,
type: "object",
author: "HominioAlpha",
prev: null,
Expand Down
96 changes: 96 additions & 0 deletions apps/api/.wundergraph/operations/insertObject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { createOperation, z } from '../generated/wundergraph.factory';
import Ajv from 'ajv';
import addFormats from 'ajv-formats';

const ajv = new Ajv({
schemaId: '$id',
strict: false,
validateSchema: false,
addUsedSchema: false
});
addFormats(ajv);

export default createOperation.mutation({
input: z.object({
object: z.any()
}),
handler: async ({ input, context, operations }) => {
try {
console.log('Step 1: Received input object:', JSON.stringify(input.object, null, 2));

if (!input.object.$schema) {
throw new Error('Object must have a $schema property');
}
console.log('Step 2: Validated $schema property exists:', input.object.$schema);

// Fetch the schema
console.log('Step 3: Fetching schema from database...');
const { data: schemaData, error: schemaError } = await context.supabase
.from('db')
.select('json')
.eq('json->>$id', input.object.$schema)
.single();

if (schemaError) {
throw new Error('Failed to fetch schema: ' + schemaError.message);
}
console.log('Step 4: Schema fetched successfully:', JSON.stringify(schemaData.json, null, 2));

const schema = schemaData.json;

// Calculate CID for the object
console.log('Step 5: Calculating CID for the object...');
const calcCIDResult = await operations.mutate({
operationName: 'calculateCID',
input: { json: input.object },
});

if (!calcCIDResult.data?.success) {
throw new Error('Failed to calculate CID: ' + (calcCIDResult.data?.error || 'Unknown error'));
}
console.log('Step 6: CID calculated successfully:', calcCIDResult.data.json.$id);

const objectWithId = {
...calcCIDResult.data.json,
$id: calcCIDResult.data.json.$id,
$schema: input.object.$schema
};
console.log('Step 7: Created object with ID:', JSON.stringify(objectWithId, null, 2));

// Validate the object against the schema
console.log('Step 8: Validating object against schema...');
const validate = ajv.compile(schema);
const valid = validate(objectWithId);

if (!valid) {
console.error('Validation errors:', ajv.errorsText(validate.errors));
throw new Error('Validation error: ' + ajv.errorsText(validate.errors));
}
console.log('Step 9: Object validated successfully against schema');

// Insert the object into the database
console.log('Step 10: Inserting object into database...');
const { data, error } = await context.supabase
.from('db')
.insert({ json: objectWithId })
.select();

if (error) {
throw new Error('Database insert error: ' + error.message);
}
console.log('Step 11: Object inserted successfully:', JSON.stringify(data[0], null, 2));

return {
success: true,
insertedData: data[0]
};
} catch (error) {
console.error('Unexpected error in insertObject:', error);
return {
success: false,
error: 'Unexpected error',
details: error.message
};
}
},
});
54 changes: 53 additions & 1 deletion apps/app/src/lib/components/HominioDB.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
operationName: 'insertDB'
});
const insertObjectMutation = createMutation({
operationName: 'insertObject'
});
function sortByTimestamp(a, b) {
return new Date(b.json.timestamp).getTime() - new Date(a.json.timestamp).getTime();
}
Expand Down Expand Up @@ -94,13 +98,61 @@
console.log('HominioDB: Selected item changed, resetting expandedProperties');
expandedProperties = [];
}
async function insertHardcodedObject() {
message = { text: '', type: '' };
const hardcodedObject = {
$schema: 'https://alpha.ipfs.homin.io/QmWqLHcJsrMpmZrbxfMA3oM2YVbHjJfGw94UbZgBwm1mYR',
$id: '', // This will be filled by the server
prev: null,
type: 'object',
title: 'John Doe User Object',
author: 'HominioDB Client',
version: 1,
description: 'A sample user object for John Doe',
properties: {
username: 'john_doe',
email: '[email protected]',
password: 'hashedpassword123',
profile: {
fullName: 'John Doe',
birthDate: '1990-01-01',
bio: "I'm a software developer who loves coding and outdoor activities.",
location: {
country: 'United States',
city: 'San Francisco'
}
},
settings: {
theme: 'dark',
notifications: true,
language: 'en'
}
}
};
const result = await $insertObjectMutation.mutateAsync({
object: hardcodedObject
});
if (result.success) {
message = { text: 'Hardcoded object inserted successfully!', type: 'success' };
await $query.refetch();
} else {
message = { text: `Failed: ${result.details}`, type: 'error' };
console.error('Failed:', result.details);
}
}
</script>

<div class="flex h-full text-gray-900 bg-tertiary-100 dark:bg-surface-800 dark:text-white">
<!-- Left side: List view -->
<div class="w-[300px] p-4 overflow-y-auto border-r border-surface-300-600-token">
<button on:click={generateRandomObject} class="mb-4 btn variant-filled-primary">
Generate Random Object
Generate Schema
</button>
<button on:click={insertHardcodedObject} class="mb-4 ml-2 btn variant-filled-secondary">
Insert Object
</button>

{#if message.text}
Expand Down
2 changes: 2 additions & 0 deletions packages/generated-wundergraph/ts-operation-errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export type OperationErrors = {
createInvite: CreateInviteErrors;
createSchema: CreateSchemaErrors;
insertDB: InsertDBErrors;
insertObject: InsertObjectErrors;
listTodos: ListTodosErrors;
queryComposer: QueryComposerErrors;
queryDB: QueryDBErrors;
Expand All @@ -34,6 +35,7 @@ export type CalculateCIDErrors = ClientOperationErrors;
export type CreateInviteErrors = ClientOperationErrors;
export type CreateSchemaErrors = ClientOperationErrors;
export type InsertDBErrors = ClientOperationErrors;
export type InsertObjectErrors = ClientOperationErrors;
export type ListTodosErrors = ClientOperationErrors;
export type QueryComposerErrors = ClientOperationErrors;
export type QueryDBErrors = ClientOperationErrors;
Expand Down

0 comments on commit fb38420

Please sign in to comment.