Skip to content
This repository has been archived by the owner on Jul 11, 2024. It is now read-only.

V3.4 tables in database #348

Open
wants to merge 2 commits into
base: v3.4
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 changes: 6 additions & 2 deletions src/crud/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,12 @@ export default function (table, schemaInformation, store) {
}

extend type Query {
${singleRowFieldName}(where: ${singleRowFieldName}_filter_input): ${table.name}
${rowsFieldName}(pagination: PaginationInput, where: ${singleRowFieldName}_filter_input, order: ${convertWordIntoSingular(table.name)}_order_input): ${table.name}List
${singleRowFieldName}(where: ${singleRowFieldName}_filter_input): ${
table.name
}
${rowsFieldName}(pagination: PaginationInput, where: ${singleRowFieldName}_filter_input, order: ${convertWordIntoSingular(
table.name
)}_order_input): ${table.name}List
count${table.name}(where: ${singleRowFieldName}_filter_input): Int
}`
},
Expand Down
13 changes: 8 additions & 5 deletions src/database/eagerLoadingGraphqlQuery.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { wertikApp } from "../store"
import { wertikApp } from "../store"
import isPlainObject from "lodash.isplainobject"
import get from "lodash.get"
import has from "lodash.has"
Expand Down Expand Up @@ -35,8 +35,8 @@ export const convertGraphqlRequestedFieldsIntoInclude = (
let order = []
let depth = []
graphqlFields = clean(graphqlFields)
let currentModel = wertikApp.models[tableName];
let currentModuleRelationshipsKeys =[]
let currentModel = wertikApp.models[tableName]
let currentModuleRelationshipsKeys = []
let allRelationshipKeys = []

for (const [modelName, model] of Object.entries(wertikApp.models)) {
Expand All @@ -59,14 +59,17 @@ export const convertGraphqlRequestedFieldsIntoInclude = (

Object.keys(_obj).forEach((key) => {
if (allRelationshipKeys.includes(key)) {
currentModel = currentModel.associations[key].target;
currentModel = currentModel.associations[key].target
depth.push(key)
let _localDepth = [...JSON.parse(JSON.stringify(depth))]
const includeParams: { [key: string]: any } = {
required: false,
model: wertikApp.models[currentModel.tableName],
as: key,
attributes: generateRequestedFieldsFromGraphqlInfo(currentModel.tableName,_obj[key]),
attributes: generateRequestedFieldsFromGraphqlInfo(
currentModel.tableName,
_obj[key]
),
include:
Object.keys(_obj[key]).length > 0 ? recursion(_obj[key]) : [],
}
Expand Down
46 changes: 28 additions & 18 deletions src/database/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,41 +77,51 @@ export const convertDatabaseTypeIntoGraphqlType = (
}
}



export const applyRelationshipsFromStoreToDatabase = async (
app: WertikApp
) => {
Object.keys(app.database).forEach(dbName => {
let db = app.database[dbName];
export const applyRelationshipsFromStoreToDatabase = async (app: WertikApp) => {
Object.keys(app.database).forEach((dbName) => {
let db = app.database[dbName]
const tables = db?.credentials?.tables || []
tables.forEach(table => {
const currentModel = app.models[table.name];
tables.forEach((table) => {
const currentModel = app.models[table.name]

for (const [relationshipType, relationships] of Object.entries(table.relationships|| {})) {
for (const [relatedTableName, relationshipOptions] of Object.entries<SqlTable['relationships']['belongsTo']>(table.relationships[relationshipType] || {})) {
const relatedTable = app.models[relatedTableName];
for (const [relationshipType, relationships] of Object.entries(
table.relationships || {}
)) {
for (const [relatedTableName, relationshipOptions] of Object.entries<
SqlTable["relationships"]["belongsTo"]
>(table.relationships[relationshipType] || {})) {
const relatedTable = app.models[relatedTableName]
if (!relatedTable) {
wLogWithError(`[DB] Related table not found:`, `model '${relatedTableName}' not found for relationship '${relationshipType}' in table '${table.name}'`)
wLogWithError(
`[DB] Related table not found:`,
`model '${relatedTableName}' not found for relationship '${relationshipType}' in table '${table.name}'`
)
process.exit()
}
wLogWithInfo(`[DB] Applying relationship:`, `${table.name}.${relationshipType}(${relatedTable.tableName},${JSON.stringify(relationshipOptions)})`)
wLogWithInfo(
`[DB] Applying relationship:`,
`${table.name}.${relationshipType}(${
relatedTable.tableName
},${JSON.stringify(relationshipOptions)})`
)
currentModel[relationshipType](relatedTable, relationshipOptions)
const isManyRelationship = ['hasMany','belongsToMany'].includes(relationshipType)
const isManyRelationship = ["hasMany", "belongsToMany"].includes(
relationshipType
)
if (isManyRelationship) {
app.store.graphql.typeDefs = app.store.graphql.typeDefs.concat(`
extend type ${table.name} {
${relationshipOptions.as}(offset: Int, limit: Int, where: ${table.name}_filter_input, order: ${table.name}_order_input): [${relatedTableName}]
}
`)
}else {
} else {
app.store.graphql.typeDefs = app.store.graphql.typeDefs.concat(`
extend type ${table.name} {
${relationshipOptions.as}: ${relatedTableName}
}`)
}
}
}
});
});
})
})
}
6 changes: 2 additions & 4 deletions src/database/mysql/getTableInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,7 @@ export const getMysqlTableInfo = async (
const fields: TableInfo["columns"] = (
rows as MysqlColumnInfoDescribeTable[]
).map((element) => {
const graphqlType = convertDatabaseTypeIntoGraphqlType(
element,
tableName
)
const graphqlType = convertDatabaseTypeIntoGraphqlType(element, tableName)
let isPrimary = element.Key === "PRI"
const isNull = element.Null === "YES"

Expand All @@ -59,6 +56,7 @@ export const getMysqlTableInfo = async (
databaseType: graphqlType.databaseType,
isPrimary: isPrimary,
isDateColumn: graphqlType.isDateColumn,
extra: element.Extra,
} as TableInfo["columns"][0]
})

Expand Down
12 changes: 5 additions & 7 deletions src/database/mysql/mysql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ export const withMysqlDatabase = function (obj: WithMysqlDatabaseProps) {
})
let models: ModelCtor<Model<any, any>>[] = []
obj.tables?.forEach(async (table) => {

let graphqlSchema = [`type ${table.name} {`]
let listSchema = ""
let filterSchema = [
Expand All @@ -67,9 +66,10 @@ export const withMysqlDatabase = function (obj: WithMysqlDatabaseProps) {
// if (column.columnName === "id") return

if (column.isEnum) {
wertikApp.store.graphql.typeDefs = wertikApp.store.graphql.typeDefs.concat(
generateEnumTypeForGraphql(column)
)
wertikApp.store.graphql.typeDefs =
wertikApp.store.graphql.typeDefs.concat(
generateEnumTypeForGraphql(column)
)
}

updateSchema = getUpdateSchema(table, tableInfo)
Expand All @@ -85,14 +85,13 @@ export const withMysqlDatabase = function (obj: WithMysqlDatabaseProps) {
column.columnName
}: ${column.graphqlType.toLowerCase()}_filter_input`

filterSchema.push(filter_input)

fields[column.columnName] = {
type: column.databaseType,
allowNull: column.isNull,
defaultValue: column.default,
primaryKey: column.isPrimary,
values: column.isEnum ? column.enumValues : null,
autoIncrement: column.extra === "auto_increment",
}
})
graphqlSchema.push("}")
Expand All @@ -110,7 +109,6 @@ export const withMysqlDatabase = function (obj: WithMysqlDatabaseProps) {
}
)


wertikApp.models[table.name] = tableInstance
const schemaInformation = {
moduleName: table.name,
Expand Down
90 changes: 24 additions & 66 deletions src/devServer.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require("dotenv").config()

import wertik, {
withMysqlDatabase,
withApolloGraphql,
Expand All @@ -18,36 +20,36 @@ wertik({
storeTypeDefFilePath: process.cwd() + "/graphqlSchema.graphql",
}),
database: {
wertik: withMysqlDatabase({
port: 3306,
name: "wertik_test",
host: "127.0.0.1",
password: "pass",
username: "root",
ecommerce: withMysqlDatabase({
name: process.env.TEST_DATABASE_NAME,
host: process.env.TEST_DATABASE_HOST,
password: process.env.TEST_DATABASE_PASSWORD,
port: +process.env.TEST_DATABASE_PORT,
username: process.env.TEST_DATABASE_USERNAME,
tables: [
{
name: "user",
name: process.env.TEST_DATABASE_TABLE_PRODUCT,
relationships: {
belongsTo: {
user: {
as: "user",
foreignKey: "user_id",
targetKey: "id",
},
},
},
},
{
name: process.env.TEST_DATABASE_TABLE_USER,
relationships: {
hasMany: {
product: {
as: "products",
foreignKey: "user_id",
sourceKey: "id",
}
}
}
},
{
name: "product",
relationships: {
hasOne: {
user: {
as: "user",
foreignKey: "id",
sourceKey: "user_id",
}
}
}
},
},
},
},
],
}),
Expand All @@ -59,50 +61,6 @@ wertik({
port: 3306,
}),
},
// modules: modules,
// Product: withModule({
// name: "Product",
// useDatabase: true,
// database: "wertik",
// table: "product",
// on: function ({ belongsTo }) {
// belongsTo({
// database: "wertik",
// graphqlKey: "user",
// module: "User",
// options: {
// as: "user",
// foreignKey: "user_id",
// targetKey: "id",
// },
// })
// },
// }),
// User: withModule({
// name: "User",
// useDatabase: true,
// database: "wertik",
// table: "user",
// on: function ({ hasMany }) {
// hasMany({
// database: "wertik",
// graphqlKey: "products",
// module: "Product",
// options: {
// as: "products",
// foreignKey: "user_id",
// sourceKey: "id",
// },
// })
// },
// }),
// Category: withModule({
// name: "Category",
// useDatabase: true,
// database: "wertik",
// table: "category",
// }),
// },
sockets: {
mySockets: withWebSockets({
path: "/websockets",
Expand Down
21 changes: 10 additions & 11 deletions src/graphql/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,7 @@ import {
import { wLogWithSuccess } from "../utils/log"

export const withApolloGraphql = (props?: WithApolloGraphqlProps) => {
return ({
wertikApp,
expressApp,
configuration,
}: GraphqlInitializeProps) => {
return ({ wertikApp, expressApp, configuration }: GraphqlInitializeProps) => {
const depthLimit = get(props, "validation.depthLimit", 7)
props = props ? props : {}
wertikApp.store.graphql.typeDefs = wertikApp.store.graphql.typeDefs.concat(
Expand All @@ -39,12 +35,15 @@ export const withApolloGraphql = (props?: WithApolloGraphqlProps) => {
if (props && props.storeTypeDefFilePath) {
if (fs.existsSync(props.storeTypeDefFilePath))
fs.unlinkSync(props.storeTypeDefFilePath)

const formattedTypeDefs = prettier.format(wertikApp.store.graphql.typeDefs, {
filepath: props.storeTypeDefFilePath,
semi: false,
parser: "graphql",
})

const formattedTypeDefs = prettier.format(
wertikApp.store.graphql.typeDefs,
{
filepath: props.storeTypeDefFilePath,
semi: false,
parser: "graphql",
}
)
fs.writeFileSync(props.storeTypeDefFilePath, formattedTypeDefs)
}

Expand Down
23 changes: 0 additions & 23 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,41 +167,18 @@ const Wertik: (configuration?: WertikConfiguration) => Promise<WertikApp> = (
})
}

let stopServer = () => {
wLogWithInfo(`[Wertik-App]`, `Stopping server`)
httpServer.close(() => {
wLogWithSuccess(`[Wertik-App]`, `Server stopped`)
process.exit()
})
}

let restartServer = () => {
wLogWithInfo(`[Wertik-App]`, `Restarting server`)
httpServer.close(() => {
setTimeout(() => {
startServer()
}, 500)
})
}

if (!new Object(process.env).hasOwnProperty("TEST_MODE")) {
setTimeout(async () => {
if (selfStart === true) {
startServer()
}
resolve({
...wertikApp,
restartServer,
stopServer,
startServer,
})
}, 500)
} else {
resolve({
...wertikApp,
restartServer,
stopServer,
startServer,
})
}
} catch (e) {
Expand Down
4 changes: 1 addition & 3 deletions src/modules/modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,7 @@ export const withModule = (moduleProps: WithModuleProps) => {
let graphqlSchema = [`type ${moduleProps.name} {`]
let listSchema = ""
let filterSchema = [
`input ${convertWordIntoSingular(
moduleProps.name
)}_filter_input {`,
`input ${convertWordIntoSingular(moduleProps.name)}_filter_input {`,
]
let orderSchema = ""

Expand Down
Loading