Skip to content

Commit

Permalink
Merge pull request #183 from konecty/feature/apply-meta
Browse files Browse the repository at this point in the history
Feature/apply meta
  • Loading branch information
7sete7 authored Oct 31, 2024
2 parents 3d1b495 + 13470c2 commit 3043202
Show file tree
Hide file tree
Showing 6 changed files with 163 additions and 8 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ module.exports = {
'@typescript-eslint/no-unsafe-call': 'off',
'no-case-declarations': 'off',
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/ban-types': 'warn',
},
settings: {
'import/parsers': {
Expand Down
28 changes: 24 additions & 4 deletions src/imports/meta/loadMetaObjects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,18 +95,38 @@ async function dbLoad() {
function dbWatch() {
MetaObject.MetaObject.watch().on('change', async (change: any) => {
if (change.operationType === 'delete') {
switch (change.fullDocumentBeforeChange.type) {
const id = change.documentKey._id as string;

let meta: any = null;

if (id in MetaObject.DisplayMeta) {
meta = MetaObject.DisplayMeta[id];
}

if (id in MetaObject.Meta) {
meta = MetaObject.Meta[id];
}

if (id in MetaObject.Access) {
meta = MetaObject.Access[id];
}

if (id in MetaObject.MetaByCollection) {
meta = MetaObject.MetaByCollection[id];
}

switch (meta?.type) {
case 'access':
unset(MetaObject.Access, change.fullDocumentBeforeChange._id);
unset(MetaObject.Access, id);
break;
case 'document':
case 'composite':
deregisterMeta(change.fullDocumentBeforeChange);
deregisterMeta(meta);
break;
case 'pivot':
case 'view':
case 'list':
unset(MetaObject.DisplayMeta, change.fullDocumentBeforeChange._id);
unset(MetaObject.DisplayMeta, id);
break;
}
} else if (change.operationType === 'insert') {
Expand Down
19 changes: 16 additions & 3 deletions src/imports/model/Filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,33 @@ import { z } from 'zod';
export const Condition = z.object({
term: z.string(),
operator: z.string(),
value: z.union([z.string(), z.number(), z.boolean(), z.array(z.union([z.string(), z.number(), z.boolean()]))]),
value: z
.union([z.string(), z.number(), z.boolean(), z.any(), z.array(z.union([z.string(), z.number(), z.boolean()]))])
.optional()
.nullable(),
editable: z.boolean().optional(),
disabled: z.boolean().optional(),
sort: z.number().optional(),
style: z
.object({
// renderAs: z.enum(['checbox', 'lookupfield', 'datetimefield', 'textfield', 'radiobox']).optional(),
renderAs: z.string().optional(), // o ideal seria mapear todos as possibilidades
columns: z.number().optional(),
hideOnDisable: z.boolean().optional(),
customLabel: z.string().optional(),
})
.optional(),
});

export const KonFilter = z.object({
match: z.literal('and').or(z.literal('or')),
conditions: z.array(Condition).optional(),
conditions: z.array(Condition).optional().or(z.record(Condition).optional()),
textSearch: z.string().optional(),
filters: z
.array(
z.object({
match: z.literal('and').or(z.literal('or')).optional(),
conditions: z.array(Condition).optional(),
conditions: z.array(Condition).optional().or(z.record(Condition).optional()),
textSearch: z.string().optional(),
}),
)
Expand Down
2 changes: 2 additions & 0 deletions src/imports/model/Form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ export const FormSchema = z.object({
icon: z.string().optional(),
visuals: z.array(VisualsSchema).optional(),
collection: z.string().optional(),
namespace: z.array(z.string()).optional(),
parent: z.string().optional(),
});

export type Form = z.infer<typeof FormSchema>;
4 changes: 3 additions & 1 deletion src/imports/model/List.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { z } from 'zod';
import { KonFilter } from './Filter';
import { LabelSchema } from './Label';
import { KonFilter } from './Filter';

export const ListSchema = z.object({
type: z.literal('list'),
Expand All @@ -11,6 +11,8 @@ export const ListSchema = z.object({
name: z.string(),
label: LabelSchema,
plurals: LabelSchema,
loadDataAtOpen: z.boolean().optional(),
namespace: z.array(z.string()).optional(),
icon: z.string().optional(),
refreshRate: z.object({
options: z.array(z.number()),
Expand Down
117 changes: 117 additions & 0 deletions src/server/routes/api/document/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import fp from 'fastify-plugin';
import { getUserFromRequest } from '@imports/auth/getUser';
import { getDocument } from '@imports/document';
import { logger } from '@imports/utils/logger';
import { WithoutId } from 'mongodb';
import { loadMetaObjects } from '@imports/meta/loadMetaObjects';
import { MetaObject } from '@imports/model/MetaObject';
import { MetaObjectSchema, MetaObjectType } from '@imports/types/metadata';

const documentAPi: FastifyPluginCallback = async fastify => {
fastify.get<{ Params: { name: string } }>('/api/document/:name', async (req, reply) => {
Expand Down Expand Up @@ -40,6 +44,119 @@ const documentAPi: FastifyPluginCallback = async fastify => {
return reply.status(500).send('Internal server error');
}
});

fastify.post<{ Params: { id: string } }>('/api/document/:id', async (req, reply) => {
if (req.originalUrl == null || req.params == null) {
return reply.status(404).send('Not found');
}

const id = req.params.id;

if (id == null) {
return reply.status(400).send('Bad request');
}

try {
const user = await getUserFromRequest(req);

if (user == null || user.admin !== true) {
return reply.status(401).send('Unauthorized');
}

const document = req.body as MetaObjectType;

if (document == null) {
return reply.status(400).send('Bad request');
}

const parsed = MetaObjectSchema.safeParse(document);

if (parsed.success === false) {
logger.error(`Error parsing document: ${parsed.error.errors.map(e => `${e.path}, ${e.code}: ${e.message}`).join('| ')}`);
return reply.status(400).send('Bad request');
}

const result = await MetaObject.MetaObject.replaceOne({ _id: id }, document as WithoutId<MetaObjectType>, { upsert: true });

if (result.upsertedCount === 1) {
return reply.status(201).send('Created');
}

if (result.modifiedCount === 1) {
return reply.send('Updated');
}

if (result.modifiedCount === 0) {
return reply.send('Not modified');
}
} catch (error) {
if (/^\[get-user\]/.test((error as Error).message)) {
return reply.status(401).send('Unauthorized');
}

logger.error(error, `Error updating document with id ${id}`);
}
return reply.status(500).send('Internal server error');
});

fastify.delete<{ Params: { id: string } }>('/api/document/:id', async (req, reply) => {
if (req.originalUrl == null || req.params == null) {
return reply.status(404).send('Not found');
}

const id = req.params.id;

if (id == null) {
return reply.status(400).send('Bad request');
}

try {
const user = await getUserFromRequest(req);

if (user == null || user.admin !== true) {
return reply.status(401).send('Unauthorized');
}

const result = await MetaObject.MetaObject.deleteOne({ _id: id });

if (result.deletedCount === 0) {
return reply.status(404).send('Not found');
}
return reply.status(200).send('Deleted');
} catch (error) {
if (/^\[get-user\]/.test((error as Error).message)) {
return reply.status(401).send('Unauthorized');
}

logger.error(error, `Error deleting document with id ${id}`);
}
return reply.status(500).send('Internal server error');
});

fastify.get<{ Params: { id: string } }>('/api/document/rebuild-references', async (req, reply) => {
if (req.originalUrl == null || req.params == null) {
return reply.status(404).send('Not found');
}

try {
const user = await getUserFromRequest(req);

if (user == null || user.admin !== true) {
return reply.status(401).send('Unauthorized');
}

await loadMetaObjects();

return reply.status(200).send('Rebuilt');
} catch (error) {
if (/^\[get-user\]/.test((error as Error).message)) {
return reply.status(401).send('Unauthorized');
}

logger.error(error, `Error rebuilding references`);
}
return reply.status(500).send('Internal server error');
});
};

export default fp(documentAPi);

0 comments on commit 3043202

Please sign in to comment.