Skip to content

Commit

Permalink
fix ddd routes (#6663)
Browse files Browse the repository at this point in the history
Co-authored-by: rotorsoft <[email protected]>
  • Loading branch information
Rotorsoft and rotorsoft authored Feb 8, 2024
1 parent 98c35b5 commit 019de34
Show file tree
Hide file tree
Showing 15 changed files with 69 additions and 48 deletions.
17 changes: 11 additions & 6 deletions libs/adapters/src/express/command.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { command, type CommandMetadata, type User } from '@hicommonwealth/core';
import type { Request, RequestHandler, Response } from 'express';
import type { NextFunction, Request, RequestHandler, Response } from 'express';
import { z, ZodSchema } from 'zod';

/**
Expand All @@ -21,10 +21,15 @@ export const expressCommand =
}
>,
res: Response<Partial<T> | undefined>,
next: NextFunction,
) => {
const results = await command(md, req.params.id, req.body, {
user: req.user as User,
address_id: req.body.address_id,
});
return res.json(results);
try {
const results = await command(md, req.params.id, req.body, {
user: req.user as User,
address_id: req.body.address_id,
});
return res.json(results);
} catch (error) {
next(error);
}
};
24 changes: 19 additions & 5 deletions libs/adapters/src/express/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { INVALID_INPUT_ERROR, stats } from '@hicommonwealth/core';
import {
INVALID_ACTOR_ERROR,
INVALID_INPUT_ERROR,
stats,
} from '@hicommonwealth/core';
import { NextFunction, Request, Response } from 'express';
import { BadRequest, InternalServerError } from './http';
import { BadRequest, InternalServerError, Unauthorized } from './http';

/**
* Captures traffic and latency
Expand All @@ -19,7 +23,7 @@ export const statsMiddleware = (
stats().histogram(`cw.path.latency`, latency, { path });
});
} catch (err: unknown) {
console.error(err);
console.error(err); // don't use logger port here
}
next();
};
Expand All @@ -33,7 +37,7 @@ export const errorMiddleware = (
res: Response,
next: NextFunction,
): void => {
console.error(error);
console.error(error); // don't use logger port here
if (res.headersSent) return next(error);

let response = InternalServerError(
Expand All @@ -44,8 +48,18 @@ export const errorMiddleware = (
switch (name) {
case INVALID_INPUT_ERROR:
response = BadRequest(message, 'details' in error && error.details);
break;

case INVALID_ACTOR_ERROR:
response = Unauthorized(message);
break;

default:
response = InternalServerError(
message,
process.env.NODE_ENV !== 'production' ? stack : undefined,
);
}
response = InternalServerError(message, stack);
}
res.status(response.status).send(response);
};
23 changes: 14 additions & 9 deletions libs/adapters/src/express/query.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { query, type QueryMetadata, type User } from '@hicommonwealth/core';
import type { Request, RequestHandler, Response } from 'express';
import type { NextFunction, Request, RequestHandler, Response } from 'express';
import { z, ZodSchema } from 'zod';

/**
Expand All @@ -12,13 +12,18 @@ export const expressQuery =
async (
req: Request<Partial<z.infer<P>>, T, Partial<z.infer<P>>>,
res: Response<T | undefined>,
next: NextFunction,
) => {
const results = await query(
md,
{ ...req.body, ...req.params } as z.infer<P>,
{
user: req.user as User,
},
);
return res.json(results);
try {
const results = await query(
md,
{ ...req.body, ...req.params } as z.infer<P>,
{
user: req.user as User,
},
);
return res.json(results);
} catch (error) {
next(error);
}
};
5 changes: 4 additions & 1 deletion libs/core/src/framework/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ export const query = async <T, P extends ZodSchema>(
actor: Actor,
): Promise<T | undefined> => {
try {
const context: QueryContext<P> = { actor, payload: schema.parse(payload) };
const validated = Object.fromEntries(
Object.entries(schema.parse(payload)).filter(([, v]) => v !== undefined),
);
const context: QueryContext<P> = { actor, payload: validated };
for (const fn of auth) {
await fn(context);
}
Expand Down
4 changes: 2 additions & 2 deletions libs/model/src/comment/CreateComment.command.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { type CommandMetadata } from '@hicommonwealth/core';
import { z } from 'zod';
import { models } from '../database';
import { MustNotExist } from '../middleware/invariants';
import { mustNotExist } from '../middleware/guards';
import type { CommentAttributes } from '../models';

const schema = z.object({
Expand All @@ -15,7 +15,7 @@ export const CreateComment: CommandMetadata<CommentAttributes, typeof schema> =
body: async ({ id, payload }) => {
const comment = await models.Comment.findOne({ where: { id } });

MustNotExist('Comment', comment);
mustNotExist('Comment', comment);

//await models.Comment.create(payload)
return payload as Partial<CommentAttributes>;
Expand Down
4 changes: 2 additions & 2 deletions libs/model/src/community/CreateCommunity.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
} from '@hicommonwealth/core';
import { z } from 'zod';
import { models } from '../database';
import { MustNotExist } from '../middleware/invariants';
import { mustNotExist } from '../middleware/guards';
import type { CommunityAttributes } from '../models';
import { checkIconSize } from '../utils/checkIconSize';
import { ALL_COMMUNITIES } from '../utils/constants';
Expand Down Expand Up @@ -65,7 +65,7 @@ export const CreateCommunity: CommandMetadata<
body: async ({ id, payload }) => {
const community = await models.Community.findOne({ where: { id } });

MustNotExist('Community', community);
mustNotExist('Community', community);

//await models.Community.create(payload)
return payload as Partial<CommunityAttributes>;
Expand Down
4 changes: 2 additions & 2 deletions libs/model/src/community/SetCommunityNamespace.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { CommandMetadata } from '@hicommonwealth/core';
import { z } from 'zod';
import { models } from '../database';
import { isCommunityAdmin } from '../middleware';
import { MustExist } from '../middleware/invariants';
import { mustExist } from '../middleware/guards';
import type { CommunityAttributes } from '../models';

export const schema = z.object({
Expand All @@ -20,7 +20,7 @@ export const SetCommunityNamespace: CommandMetadata<
body: async ({ id, payload }) => {
const community = await models.Community.findOne({ where: { id } });

if (!MustExist('Community', community)) return;
if (!mustExist('Community', community)) return;

// TODO: validate contract
// call protocol api and resolve if tbc should be a singleton
Expand Down
4 changes: 2 additions & 2 deletions libs/model/src/community/SetCommunityStake.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { CommandMetadata, InvalidState } from '@hicommonwealth/core';
import { z } from 'zod';
import { models } from '../database';
import { isCommunityAdmin } from '../middleware';
import { MustExist } from '../middleware/invariants';
import { mustExist } from '../middleware/guards';
import { CommunityAttributes } from '../models';
import { validateCommunityStakeConfig } from '../services/commonProtocol/communityStakeConfigValidator';

Expand Down Expand Up @@ -38,7 +38,7 @@ export const SetCommunityStake: CommandMetadata<
});

// !domain logic - invariants on loaded state & payload
if (!MustExist('Community', community)) return;
if (!mustExist('Community', community)) return;
if (
community.CommunityStakes &&
community.CommunityStakes.find((s) => s.stake_id === payload.stake_id)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { InvalidState } from '@hicommonwealth/core';

export const MustExist = <T>(subject: string, state?: T | null): state is T => {
export const mustExist = <T>(subject: string, state?: T | null): state is T => {
if (!state) throw new InvalidState(`${subject} must exist`, state);
return true;
};

export const MustNotExist = <T>(subject: string, state?: T | null) => {
export const mustNotExist = <T>(subject: string, state?: T | null) => {
if (state) throw new InvalidState(`${subject} must not exist`, state);
};
4 changes: 2 additions & 2 deletions libs/model/src/reaction/CreateReaction.command.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { type CommandMetadata } from '@hicommonwealth/core';
import { z } from 'zod';
import { models } from '../database';
import { MustNotExist } from '../middleware/invariants';
import { mustNotExist } from '../middleware/guards';
import type { ReactionAttributes } from '../models';

export const schema = z.object({
Expand All @@ -17,7 +17,7 @@ export const CreateReaction: CommandMetadata<
body: async ({ id, payload }) => {
const reaction = await models.Reaction.findOne({ where: { id } });

MustNotExist('Reaction', reaction);
mustNotExist('Reaction', reaction);

//await models.Reaction.create(payload)
return payload as Partial<ReactionAttributes>;
Expand Down
4 changes: 2 additions & 2 deletions libs/model/src/thread/CreateThread.command.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { type CommandMetadata } from '@hicommonwealth/core';
import { z } from 'zod';
import { models } from '../database';
import { MustNotExist } from '../middleware/invariants';
import { mustNotExist } from '../middleware/guards';
import type { ThreadAttributes } from '../models';

export const schema = z.object({
Expand All @@ -14,7 +14,7 @@ export const CreateThread: CommandMetadata<ThreadAttributes, typeof schema> = {
body: async ({ id, payload }) => {
const thread = await models.Thread.findOne({ where: { id } });

MustNotExist('Thread', thread);
mustNotExist('Thread', thread);

//await models.Thread.create(payload)
return payload as Partial<ThreadAttributes>;
Expand Down
4 changes: 2 additions & 2 deletions libs/model/src/user/CreateUser.command.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { type CommandMetadata } from '@hicommonwealth/core';
import { z } from 'zod';
import { models } from '../database';
import { MustNotExist } from '../middleware/invariants';
import { mustNotExist } from '../middleware/guards';
import type { UserAttributes } from '../models';

export const schema = z.object({
Expand All @@ -14,7 +14,7 @@ export const CreateUser: CommandMetadata<UserAttributes, typeof schema> = {
body: async ({ id, payload }) => {
const user = await models.User.findOne({ where: { id } });

MustNotExist('User', user);
mustNotExist('User', user);

//await models.User.create(payload)
return payload as Partial<UserAttributes>;
Expand Down
7 changes: 0 additions & 7 deletions packages/commonwealth/server/routes/ddd/community.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,6 @@ import passport from 'passport';

const router = Router();

//router.put('/:id', expressCommand(Community.CreateCommunity));

//router.post(
// '/set-community-namespace/:id',
// expressCommand(Community.SetCommunityNamespace),
//);

router.get(
'/:community_id/stake/:stake_id?',
passport.authenticate('jwt', { session: false }),
Expand Down
3 changes: 2 additions & 1 deletion packages/commonwealth/server/routes/ddd/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { statsMiddleware } from '@hicommonwealth/adapters';
import { errorMiddleware, statsMiddleware } from '@hicommonwealth/adapters';
import { Router } from 'express';
import community from './community';

const router = Router();

// sub-routes
router.use('/community', statsMiddleware, community);
router.use(errorMiddleware);

export default router;
6 changes: 3 additions & 3 deletions packages/commonwealth/server/routing/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1285,11 +1285,11 @@ function setupRouter(
);

app.use(endpoint, router);

// ddd-routes
app.use('/', ddd);
app.use('/ddd', ddd);

app.use(methodNotAllowedMiddleware());
// catch-all and format errors - TODO: fix unit tests
// app.use(errorMiddleware);
}

export default setupRouter;

0 comments on commit 019de34

Please sign in to comment.