Skip to content

[WIP] Adding Typeorm #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8,686 changes: 8,266 additions & 420 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,16 @@
]
},
"dependencies": {
"chalk": "^4.1.2",
"compression": "^1.7.4",
"cookie-parser": "^1.4.5",
"express": "^4.17.1",
"faker": "^5.4.0",
"mongodb": "^3.6.4",
"morgan": "^1.10.0",
"prop-types": "^15.7.2",
"react-reconciler": "^0.26.1"
"react-reconciler": "^0.26.1",
"typeorm": "^0.2.31"
},
"peerDependencies": {
"react": "^17.0.1",
Expand Down
2 changes: 1 addition & 1 deletion src/components/Error.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const isDev = process.env.NODE_ENV !== 'production';
const color = '#83CD29';
const msgStyle = { backgroundColor: '#222', color, padding: 5, borderRadius: 4, fontSize: 15 };

export const Error = ({ title, msg, error }) => (
export const ErrorMsg = ({ title, msg, error }) => (
<div
style={{
width: '100vw',
Expand Down
4 changes: 4 additions & 0 deletions src/components/Logger.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import React from 'react';
import PropTypes from 'prop-types';

export const ConsoleLog = ({ children, color, bgColor }) => (
<param$ type="console.log" content={{ children, color, bgColor }} />
);

/**
* @param {{
* mode: 'skip' | 'stream' | 'combined' | 'common' | 'dev' | 'short' | 'tiny'
Expand Down
8 changes: 8 additions & 0 deletions src/components/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,12 @@ export const CTYPES = {
param: 'param$',
logger: 'logger$',
static: 'static$',
// typeorm
typeorm: {
start: 'typeormStart$',
connection: 'typeormConnection$',
entity: 'typeormEntity$',
column: 'typeormColumn$',
entityCreate: 'typeormEntityCreate$',
},
};
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './renderer';
export * from './components';
export * from './context';
export * from './typeorm';
77 changes: 74 additions & 3 deletions src/renderer/generateRoute.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,77 @@
import React from 'react';
import chalk from 'chalk';
import { replaceValues } from '../utils/propsUtil';
import { renderPage } from './renderPage';
import { log } from './helpers';
import { Error } from '../components/Error';
import { ErrorMsg } from '../components/Error';
import { typeormParams } from './typeormParams';

function paramfn(sq, req, res, next, options) {
async function paramfn(sq, req, res, next, options) {
// eslint-disable-next-line no-restricted-syntax
for (const param of sq) {
switch (param.type) {
case 'console.log': {
const colors = [
'black',
'red',
'green',
'yellow',
'blue',
'magenta',
'cyan',
'white',
'blackBright',
'redBright',
'greenBright',
'yellowBright',
'blueBright',
'magentaBright',
'cyanBright',
'whiteBright',
];

const bgColors = [
'bgBlack',
'bgRed',
'bgGreen',
'bgYellow',
'bgBlue',
'bgMagenta',
'bgCyan',
'bgWhite',
'bgBlackBright',
'bgRedBright',
'bgGreenBright',
'bgYellowBright',
'bgBlueBright',
'bgMagentaBright',
'bgCyanBright',
'bgWhiteBright',
];

if (!!param.content.color && !colors.includes(param.content.color))
throw new Error(`Wrong color value. Available colors: ${colors.join(', ')}`);
if (!!param.content.bgColor && !bgColors.includes(param.content.bgColor))
throw new Error(`Wrong background color value. Available colors: ${bgColors.join(', ')}`);

const logContent =
typeof param.content.children === 'function'
? param.content.children(req)
: param.content.children;
const key1 = param.content.color;
const key2 = param.content.bgColor;

if (!!key1 && !!key2) {
console.log(chalk[key1][key2](logContent));
} else if (key1) {
console.log(chalk[key1](logContent));
} else if (key2) {
console.log(chalk[key2](logContent));
} else {
console.log(logContent);
}
break;
}
case 'header':
res.setHeader(param.content.name, param.content.value);
break;
Expand Down Expand Up @@ -40,6 +104,11 @@ function paramfn(sq, req, res, next, options) {
});
break;
default:
break;
}

if (param.type.includes('typeorm')) {
typeormParams(param, req, res);
}
}
}
Expand All @@ -65,7 +134,9 @@ export function generateRoute(router, props, options = {}) {
res.writableEnded = true;
res.statusCode = 500;
if (props.method === 'get') {
res.end(renderPage(() => <Error msg={msg} error={error} />, { req, res }, options));
res.end(
renderPage(() => <ErrorMsg msg={msg} error={error} />, { req, res }, options)
);
} else {
res.end(msg);
}
Expand Down
22 changes: 14 additions & 8 deletions src/renderer/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,15 @@ import { log } from './helpers';
import { generateRoute } from './generateRoute';
import { renderHTML } from './renderHTML';
import { CTYPES } from '../components/constants';
import { typeormCreateInstance, typeormAppendInitialChild } from '../typeorm/typeormHook';

let options = {
appHOC: (Component) => <Component />,
renderHTML,
};

let app;

const reconciler = ReactReconciler({
getRootHostContext(rootContainerInstance) {},
getChildHostContext(parentHostContext, type, rootContainerInstance) {},
Expand All @@ -26,7 +29,7 @@ const reconciler = ReactReconciler({
resetAfterCommit(containerInfo) {},
createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
if (type === CTYPES.app) {
const app = express();
app = express();
app.use(compression());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
Expand Down Expand Up @@ -86,6 +89,9 @@ const reconciler = ReactReconciler({
};
}

const typeormComponent = typeormCreateInstance(type, props, rootContainerInstance);
if (typeormComponent) return typeormComponent;

return null;
},

Expand All @@ -100,7 +106,7 @@ const reconciler = ReactReconciler({
}

if (child.type === CTYPES.route) {
generateRoute(parentInstance.routerInstance, child.props, options);
generateRoute(parentInstance.routerInstance, child.props, options, parentInstance);
return;
}

Expand All @@ -127,6 +133,11 @@ const reconciler = ReactReconciler({
}
return;
}

if (Object.values(CTYPES.typeorm).includes(child.type)) {
typeormAppendInitialChild(parentInstance, child);
return;
}
},

finalizeInitialChildren(instance, type, props, rootContainerInstance, hostContext) {},
Expand All @@ -137,12 +148,7 @@ const reconciler = ReactReconciler({
return text;
},

now: null,

isPrimaryRenderer: true,
scheduleDeferredCallback: '',
cancelDeferredCallback: '',

now: Date.now(),
supportsMutation: true,

commitMount(instance, type, newProps, internalInstanceHandle) {},
Expand Down
77 changes: 77 additions & 0 deletions src/renderer/typeormParams.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { deleteUndefineds } from '../utils/common';

export const typeormParams = (param, req, res) => {
switch (param.type) {
case 'typeorm.findOne': {
const { db } = req.app.locals;
const { entity, ...rest } = param.content;
const where = deleteUndefineds({ ...rest.where });

db.getRepository(entity)
.findOne({
...rest,
where,
})
.then((result) => {
res.json(result);
});
break;
}
case 'typeorm.find': {
const { db } = req.app.locals;
const { entity, ...rest } = param.content;
const where = deleteUndefineds({ ...rest.where });

db.getRepository(entity)
.find({
...rest,
where,
})
.then((result) => {
res.json(result);
});
break;
}
case 'typeorm.create': {
const { db } = req.app.locals;
const repo = db.getRepository(param.content.entity);
const newDocument = param.content.fields(req);
repo.save(newDocument).then((saved) => {
res.json(saved);
});
break;
}
case 'typeorm.delete': {
try {
const { db } = req.app.locals;
const params = param.content.fields(req);
const repo = db.getRepository(param.content.entity);
const where = deleteUndefineds(params);

const isID = !!params.id;

repo
.findOne(isID ? params.id : where)
.then((found) => {
if (!found) {
res.send('Nothing to remove');
return;
}

repo.remove(found).then(() => {
res.json('Removed');
});
})
.catch((err) => {
res.statusCode = 500;
res.end(err.message);
});
} catch (error) {
console.error(error.message);
}
break;
}
default:
break;
}
};
9 changes: 9 additions & 0 deletions src/typeorm/components/CRUD.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import React from 'react';

export const Create = ({ entity, fields }) => (
<param$ type="typeorm.create" content={{ entity, fields }} />
);

export const Delete = ({ entity, fields }) => (
<param$ type="typeorm.delete" content={{ entity, fields }} />
);
37 changes: 37 additions & 0 deletions src/typeorm/components/Connection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import React from 'react';

export const Connection = ({
name,
type,
host,
port,
username,
password,
url,
database,
useUnifiedTopology = false,
useNewUrlParser = false,
synchronize,
logging,
entities,
children,
}) => (
<typeormConnection$
name={name}
type={type}
host={host}
port={port}
url={url}
username={username}
password={password}
database={database}
useUnifiedTopology={useUnifiedTopology}
useNewUrlParser={useNewUrlParser}
synchronize={synchronize}
logging={logging}
entities={entities || []}
>
{children}
<typeormStart$ />
</typeormConnection$>
);
Loading