Skip to content

Commit

Permalink
published / remove functions working
Browse files Browse the repository at this point in the history
  • Loading branch information
mcnuttandrew committed Aug 29, 2023
1 parent 0243d6e commit 72d0e6d
Show file tree
Hide file tree
Showing 16 changed files with 1,036 additions and 67 deletions.
67 changes: 67 additions & 0 deletions netlify/functions/publish-instance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import {insertOne} from '../utils';
function prepareQuery(string: any) {
const parsed = JSON.parse(string);
const expectedArgs = [
'templateAuthor',
'templateName',
'templateMap',
'templateInstance',
'dataset',
'instanceCreator',
'thumbnail',
];
if (typeof parsed !== 'object') {
throw new Error('bad inputs');
}
const noUnexpectedKeys = Object.keys(parsed).every((key) => expectedArgs.includes(key));
const allExpectedKeys = expectedArgs.every((key) => Object.keys(parsed).includes(key));
if (!noUnexpectedKeys || !allExpectedKeys) {
throw new Error('bad inputs');
}
const query = {
template_creator: parsed.templateAuthor,
template_name: parsed.templateName,
name: parsed.templateInstance,
template_instance: parsed.templateMap,
instance_creator: parsed.instanceCreator,
dataset: parsed.dataset,
thumbnail: parsed.thumbnail,
};
return query;
}

export const handler = insertOne('template-instances', prepareQuery);

// export const handler: Handler = (event, context, callback) => {
// let inputs: Record<string, any>;
// try {
// inputs = parseInputs(event.body);
// } catch (e) {
// errorResponse(callback, 'Bad submit');
// return;
// }

// const query = {
// template_creator: inputs.templateAuthor,
// template_name: inputs.templateName,
// name: inputs.templateInstance,
// template_instance: inputs.templateMap,
// instance_creator: inputs.instanceCreator,
// dataset: inputs.dataset,
// thumbnail: inputs.thumbnail,
// };

// MongoClient.connect(`${DB_URL}/${DB_NAME}`)
// .then((connection) => {
// const db = connection.db(DB_NAME);
// const collection = db.collection('template-instances');
// return collection.insertOne(query).then((result) => {
// console.log(result);
// callback!(null, {statusCode: 200});
// connection.close();
// });
// })
// .catch((err) => {
// return errorResponse(callback, err);
// });
// };
21 changes: 21 additions & 0 deletions netlify/functions/publish.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import {insertOne} from '../utils';

function prepareQuery(body: any) {
const parsed = JSON.parse(body);
const {template} = parsed;
if (!template || typeof template !== 'object') {
throw new Error('bad inputs');
}
const {templateAuthor, templateName} = template;
if (!templateAuthor || !templateName) {
throw new Error('bad inputs');
}

return {
template: JSON.stringify(template),
creator: templateAuthor,
name: templateName,
};
}

export const handler = insertOne('templates', prepareQuery);
32 changes: 32 additions & 0 deletions netlify/functions/remove-instance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import {errorResponse} from '../utils';
import {Handler} from '@netlify/functions';
import {MongoClient} from 'mongodb';

const DB_URL = process.env.DB_URL || 'mongodb://localhost:27017';
const DB_NAME = 'ivy-be';

export const handler: Handler = (event, context, callback) => {
let parsedArgs: Record<string, any>;
try {
parsedArgs = JSON.parse(event.body!);
} catch (e) {
errorResponse(callback, 'Bad submit');
return;
}

MongoClient.connect(`${DB_URL}/${DB_NAME}`)
.then(async (connection) => {
const db = connection.db(DB_NAME);

await db.collection('template-instances').deleteMany({
template_name: parsedArgs.templateName,
template_creator: parsedArgs.templateAuthor,
name: parsedArgs.instanceName,
instance_creator: parsedArgs.userName,
});

callback!(null, {statusCode: 200});
connection.close();
})
.catch((err) => errorResponse(callback, err));
};
35 changes: 35 additions & 0 deletions netlify/functions/remove.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import {errorResponse} from '../utils';
import {Handler} from '@netlify/functions';
import {MongoClient} from 'mongodb';

const DB_URL = process.env.DB_URL || 'mongodb://localhost:27017';
const DB_NAME = 'ivy-be';

export const handler: Handler = (event, context, callback) => {
let parsedArgs: Record<string, any>;
try {
parsedArgs = JSON.parse(event.body!);
} catch (e) {
errorResponse(callback, 'Bad submit');
return;
}

MongoClient.connect(`${DB_URL}/${DB_NAME}`)
.then(async (connection) => {
const db = connection.db(DB_NAME);

await db.collection('templates').deleteMany({
name: parsedArgs.templateName,
creator: parsedArgs.templateAuthor,
});

await db.collection('template-instances').deleteMany({
template_name: parsedArgs.templateName,
template_creator: parsedArgs.templateAuthor,
});

callback!(null, {statusCode: 200});
connection.close();
})
.catch((err) => errorResponse(callback, err));
};
2 changes: 2 additions & 0 deletions netlify/functions/template-instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ import {getOne, getParametersFromPath} from '../utils';

function pathToQuery(path: string) {
const params = getParametersFromPath(path);
console.log(params);
const query = {
template_name: params.name,
template_creator: params.author,
name: params.instance,
};
return query;
}
Expand Down
4 changes: 2 additions & 2 deletions netlify/functions/template-instances.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import {simpleHandler} from '../utils';
import {getMany} from '../utils';

export const handler = simpleHandler('template-instances');
export const handler = getMany('template-instances');
4 changes: 2 additions & 2 deletions netlify/functions/templates.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import {simpleHandler} from '../utils';
import {getMany} from '../utils';

export const handler = simpleHandler('templates');
export const handler = getMany('templates');
88 changes: 60 additions & 28 deletions netlify/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,24 @@ export function errorResponse(callback, err) {
});
}

export const simpleHandler: (colName: string) => Handler =
(colName: string) => (event, context, callback) => {
MongoClient.connect(`${DB_URL}/${DB_NAME}`)
.then((connection) => {
const db = connection.db(DB_NAME);
const collection = db.collection(colName);

collection
.find({})
.toArray()
.then((results) => {
callback!(null, {
statusCode: 200,
body: JSON.stringify(results),
});
connection.close();
export const getMany: (colName: string) => Handler = (colName: string) => (event, context, callback) => {
MongoClient.connect(`${DB_URL}/${DB_NAME}`)
.then((connection) =>
connection
.db(DB_NAME)
.collection(colName)
.find({})
.toArray()
.then((results) => {
callback!(null, {
statusCode: 200,
body: JSON.stringify(results),
});
})
.catch((err) => errorResponse(callback, err));
};
connection.close();
}),
)
.catch((err) => errorResponse(callback, err));
};

export const getOne: (
colName: string,
Expand All @@ -61,15 +59,49 @@ export const getOne: (
const db = connection.db(DB_NAME);
const collection = db.collection(colName);

collection.findOne(query).then((result) => {
const output = resultToOutput(result);
if (output) {
callback!(null, output);
} else {
errorResponse(callback, 'Not found');
}
connection.close();
});
collection
.find(query)
.limit(1)
.sort({$natural: -1})
.toArray()
.then((result) => {
const output = resultToOutput(result[0]);
if (output) {
callback!(null, output);
} else {
errorResponse(callback, 'Not found');
}
connection.close();
});
})
.catch((err) => errorResponse(callback, err));
};

// should be formatted like 2020-09-09T04:35:08.804Z
const makeDateString = () => new Date().toISOString();

export const insertOne: (colName: string, bodyToQuery: (body: string) => Record<string, any>) => Handler =
(colName, bodyToQuery) => (event, context, callback) => {
let query: Record<string, any>;
try {
query = bodyToQuery(event.body || '');
} catch (e) {
errorResponse(callback, 'Bad submit');
return;
}

MongoClient.connect(`${DB_URL}/${DB_NAME}`)
.then(async (connection) => {
const db = connection.db(DB_NAME);
const collection = db.collection(colName);

const latestInsert = await collection.find({}).sort({id: -1}).limit(1).toArray();
const lastId = latestInsert[0]?.id || 0;

return collection.insertOne({...query, id: lastId + 1, created_at: makeDateString()}).then(() => {
callback!(null, {statusCode: 200});
connection.close();
});
})
.catch((err) => errorResponse(callback, err));
};
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,16 @@
"@typescript-eslint/parser": "^6.0.0",
"@vitejs/plugin-react": "^1.1.4",
"@vitejs/plugin-react-swc": "^3.3.2",
"ajv": "^6.12.0",
"acorn-jsx": "^5.3.2",
"babel-loader": "^8.2.3",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.7",
"eslint": "^8.44.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.1",
"jest": "^29.6.1",
"jest-fetch-mock": "^3.0.3",
"netlify-cli": "^16.1.0",
"ts-jest": "^29.1.1",
"typescript": "^5.0.2",
Expand All @@ -44,7 +48,6 @@
},
"dependencies": {
"@monaco-editor/react": "^4.5.2",
"ajv": "^6.12.0",
"d3-dsv": "^1.1.1",
"datalib": "^1.9.2",
"dom-to-image": "^2.6.0",
Expand Down Expand Up @@ -124,4 +127,4 @@
"^react-dnd-test-utils$": "react-dnd-test-utils/dist/cjs"
}
}
}
}
6 changes: 2 additions & 4 deletions src/components/tooltips/publish-instance-tooltip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ const knownDatasetName = new Set(Object.keys(VegaDatasets).concat(Object.keys(Sm

import {TemplateMap} from '../../types';

import {serverPrefix} from '../../utils';

interface Props {
templateAuthor: string;
templateName: string;
Expand Down Expand Up @@ -57,8 +55,8 @@ export default function PublishInstanceTooltip(props: Props): JSX.Element {
// TODO: require templateMap must not be blank
// TODO: require that fan out is not currently in use
const node = document.querySelector('.chart-container div');
DomToImage.toJpeg(node, {quality: 0.5}).then(templateImg => {
fetch(`${serverPrefix()}/publish-instance`, {
DomToImage.toJpeg(node, {quality: 0.5}).then((templateImg) => {
fetch(`.netlify/functions/publish-instance`, {
...POST_PARAMS,
body: JSON.stringify({
templateAuthor,
Expand Down
3 changes: 1 addition & 2 deletions src/components/tooltips/publish-template-tooltip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {POST_PARAMS} from '../../constants';

import {Template} from '../../types';
import {GenericAction} from '../../actions';
import {serverPrefix} from '../../utils';

interface Props {
template: Template;
Expand Down Expand Up @@ -36,7 +35,7 @@ export default function PublishTemplateTooltip(props: Props): JSX.Element {
{error && <h5 style={{color: 'red'}}>{error}</h5>}
<button
onClick={(): void => {
fetch(`${serverPrefix()}/publish`, {...POST_PARAMS, body: output} as any).then(() => {
fetch(`.netlify/functions/publish`, {...POST_PARAMS, body: output} as any).then(() => {
setSaved(true);
saveCurrentTemplate();
});
Expand Down
4 changes: 1 addition & 3 deletions src/components/tooltips/unpublish-instance-tooltip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import Tooltip from 'rc-tooltip';
import {TiTrash} from 'react-icons/ti';
import {POST_PARAMS} from '../../constants';

import {serverPrefix} from '../../utils';

interface Props {
templateAuthor: string;
templateName: string;
Expand Down Expand Up @@ -35,7 +33,7 @@ export default function UnpublishInstanceTooltip(props: Props): JSX.Element {
<button
type="button"
onClick={(): void => {
fetch(`${serverPrefix()}/remove`, {
fetch(`.netlify/functions/remove-instance`, {
...POST_PARAMS,
body: JSON.stringify({templateAuthor, templateName, instanceName, userName}),
} as any).then(() => {
Expand Down
3 changes: 1 addition & 2 deletions src/components/tooltips/unpublish-template-tooltip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {Link} from 'react-router-dom';

import {Template} from '../../types';
import {GenericAction} from '../../actions/index';
import {serverPrefix} from '../../utils';

interface Props {
template: Template;
Expand Down Expand Up @@ -41,7 +40,7 @@ export default function UnpublishInstanceTooltip(props: Props): JSX.Element {
<Link
to="/editor/unpublished"
onClick={(): void => {
fetch(`${serverPrefix()}/remove`, {
fetch(`.netlify/functions/remove`, {
...POST_PARAMS,
body: JSON.stringify({
templateName: template.templateName,
Expand Down
Loading

0 comments on commit 72d0e6d

Please sign in to comment.