Browse Source

run eslint

main
eiknat 2 years ago
parent
commit
672c24b919
  1. 16
      src/app.ts
  2. 4
      src/category/category.controller.ts
  3. 4
      src/category/category.model.ts
  4. 4
      src/comment/comment.controller.ts
  5. 4
      src/comment/comment.model.ts
  6. 4
      src/community/community.controller.ts
  7. 4
      src/community/community.model.ts
  8. 2
      src/database/knex.ts
  9. 6
      src/database/knexfile.ts
  10. 1
      src/database/migrations/initial_snapshot.ts
  11. 73
      src/database/seeds/00_user_test_data.ts
  12. 24
      src/database/seeds/01_site_test_data.ts
  13. 20
      src/database/seeds/02_category_test_data.ts
  14. 30
      src/database/seeds/03_community_test_data.ts
  15. 26
      src/database/seeds/04_post_test_data.ts
  16. 26
      src/database/seeds/05_comment_test_data.ts
  17. 24
      src/database/seeds/06_private-message_test_data.ts
  18. 2
      src/enums.ts
  19. 2
      src/images/images.service.ts
  20. 3
      src/lib/errors.ts
  21. 10
      src/lib/jwt.ts
  22. 4
      src/middleware/errors.middleware.ts
  23. 6
      src/middleware/user.middleware.ts
  24. 4
      src/post/post.controller.ts
  25. 4
      src/post/post.model.ts
  26. 4
      src/private-message/private-message.controller.ts
  27. 4
      src/private-message/private-message.model.ts
  28. 4
      src/site/site.controller.ts
  29. 4
      src/site/site.model.ts
  30. 4
      src/user/models/user-ban.model.ts
  31. 4
      src/user/models/user-mention.model.ts
  32. 4
      src/user/models/user-tag.model.ts
  33. 5
      src/user/models/user-token.model.ts
  34. 52
      src/user/models/user.model.ts
  35. 12
      src/user/user.controller.ts
  36. 14
      src/user/user.service.ts

16
src/app.ts

@ -1,4 +1,5 @@
import express, { Request, Response, Application } from 'express';
import * as dotenv from 'dotenv';
import { UserRoutes } from './user/user.controller';
import { getSite } from './site/site.controller';
import { getPosts } from './post/post.controller';
@ -8,22 +9,21 @@ import { getComments } from './comment/comment.controller';
import { getCategories } from './category/category.controller';
import { requireAdminOrMod, requireUserToken } from './middleware/user.middleware';
import { errorHandler } from './middleware/errors.middleware';
import * as dotenv from 'dotenv'
let path = __dirname + '/.env'
dotenv.config({ path: path });
let path = `${__dirname}/.env`;
dotenv.config({ path });
switch (process.env.NODE_ENV) {
case 'test':
path = __dirname + '/.env.test';
path = `${__dirname}/.env.test`;
break;
case 'production':
path = __dirname + '/.env.production';
path = `${__dirname}/.env.production`;
break;
default:
path = __dirname + '/.env.development';
path = `${__dirname}/.env.development`;
}
dotenv.config({ path: path });
dotenv.config({ path });
const app: Application = express();
const port: string = process.env.HB_PORT || '8080';
@ -45,5 +45,5 @@ app.use('/api/v1/users', UserRoutes);
app.use(errorHandler);
app.listen(port, () => {
console.log(`hexing on port ${port}`)
console.log(`hexing on port ${port}`);
});

4
src/category/category.controller.ts

@ -1,6 +1,4 @@
import { Request, Response } from 'express';
import { getCategoryList } from './category.model';
export const getCategories = async (req: Request, res: Response) => {
return res.json({ categories: await getCategoryList() });
}
export const getCategories = async (req: Request, res: Response) => res.json({ categories: await getCategoryList() });

4
src/category/category.model.ts

@ -5,6 +5,4 @@ export interface Category {
name: string;
}
export const getCategoryList = async (): Promise<Category[]> => {
return await knex<Category>('category');
}
export const getCategoryList = async (): Promise<Category[]> => await knex<Category>('category');

4
src/comment/comment.controller.ts

@ -1,6 +1,4 @@
import { Request, Response } from 'express';
import { getCommentList } from './comment.model';
export const getComments = async (req: Request, res: Response) => {
return res.json({ comments: await getCommentList() });
}
export const getComments = async (req: Request, res: Response) => res.json({ comments: await getCommentList() });

4
src/comment/comment.model.ts

@ -15,6 +15,4 @@ export interface Comment {
local: boolean;
}
export const getCommentList = async (): Promise<Comment[]> => {
return await knex<Comment>('comment');
}
export const getCommentList = async (): Promise<Comment[]> => await knex<Comment>('comment');

4
src/community/community.controller.ts

@ -1,6 +1,4 @@
import { Request, Response } from 'express';
import { getCommunityList } from './community.model';
export const getCommunities = async (req: Request, res: Response) => {
return res.json({ communities: await getCommunityList() });
}
export const getCommunities = async (req: Request, res: Response) => res.json({ communities: await getCommunityList() });

4
src/community/community.model.ts

@ -21,6 +21,4 @@ export interface Community {
banner?: string;
}
export const getCommunityList = async (): Promise<Community[]> => {
return await knex<Community>('community');
}
export const getCommunityList = async (): Promise<Community[]> => await knex<Community>('community');

2
src/database/knex.ts

@ -1,4 +1,4 @@
import Knex from 'knex';
import { default as KnexConfig } from './knexfile';
export const knex = Knex(KnexConfig.development);
export const knex = Knex(KnexConfig.development);

6
src/database/knexfile.ts

@ -8,14 +8,14 @@ export default {
host: '127.0.0.1',
user: 'hexbear',
password: 'hexbear',
database: 'hexbear'
database: 'hexbear',
},
migrations: {
tableName: 'knex_migrations',
directory: 'migrations',
schemaName: 'knex'
schemaName: 'knex',
},
searchPath: ['public','hexbear','utils','knex'],
searchPath: ['public', 'hexbear', 'utils', 'knex'],
},
// staging: {

1
src/database/migrations/initial_snapshot.ts

@ -5,7 +5,6 @@ export async function up(knex: Knex): Promise<void> {
await knex.schema.raw(sqlQuery);
}
export async function down(knex: Knex): Promise<void> {
await knex.schema.raw(`
drop schema hexbear cascade;

73
src/database/seeds/00_user_test_data.ts

@ -1,41 +1,40 @@
import * as Knex from 'knex';
export async function seed(knex: Knex): Promise<void> {
// Deletes ALL existing entries
await knex('user_').del();
// Deletes ALL existing entries
await knex('user_').del();
// Inserts seed entries
await knex('user_').insert([
{
id: 1,
name: 'marx',
preferred_username: 'karl',
password_encrypted: 'hunter2',
email: '[email protected]',
avatar: null,
theme: 'dark',
default_sort_type: 0,
default_listing_type: 0,
lang: 'english',
actor_id: 'http://localhost:8080/u/marx',
admin: true,
sitemod: true
},
{
id: 2,
name: 'hammer',
preferred_username: 'sickle',
password_encrypted: 'hunter1',
email: '[email protected]',
avatar: null,
theme: 'dark',
default_sort_type: 0,
default_listing_type: 0,
lang: 'english',
actor_id: 'http://localhost:8080/u/hammer',
admin: false,
sitemod: false
},
]);
};
// Inserts seed entries
await knex('user_').insert([
{
id: 1,
name: 'marx',
preferred_username: 'karl',
password_encrypted: 'hunter2',
email: '[email protected]',
avatar: null,
theme: 'dark',
default_sort_type: 0,
default_listing_type: 0,
lang: 'english',
actor_id: 'http://localhost:8080/u/marx',
admin: true,
sitemod: true,
},
{
id: 2,
name: 'hammer',
preferred_username: 'sickle',
password_encrypted: 'hunter1',
email: '[email protected]',
avatar: null,
theme: 'dark',
default_sort_type: 0,
default_listing_type: 0,
lang: 'english',
actor_id: 'http://localhost:8080/u/hammer',
admin: false,
sitemod: false,
},
]);
}

24
src/database/seeds/01_site_test_data.ts

@ -1,16 +1,16 @@
import * as Knex from 'knex';
export async function seed(knex: Knex): Promise<void> {
// Deletes ALL existing entries
await knex('site').del();
// Deletes ALL existing entries
await knex('site').del();
// Inserts seed entries
await knex('site').insert([
{
id: 1,
name: 'hexbear chat',
description: 'nothing but pig poop balls',
creator_id: 1
},
]);
};
// Inserts seed entries
await knex('site').insert([
{
id: 1,
name: 'hexbear chat',
description: 'nothing but pig poop balls',
creator_id: 1,
},
]);
}

20
src/database/seeds/02_category_test_data.ts

@ -1,14 +1,14 @@
import * as Knex from 'knex';
export async function seed(knex: Knex): Promise<void> {
// Deletes ALL existing entries
await knex('category').del();
// Deletes ALL existing entries
await knex('category').del();
// Inserts seed entries
await knex('category').insert([
{
id: 1,
name: 'Discussion'
},
]);
};
// Inserts seed entries
await knex('category').insert([
{
id: 1,
name: 'Discussion',
},
]);
}

30
src/database/seeds/03_community_test_data.ts

@ -1,19 +1,19 @@
import * as Knex from 'knex';
export async function seed(knex: Knex): Promise<void> {
// Deletes ALL existing entries
await knex('community').del();
// Deletes ALL existing entries
await knex('community').del();
// Inserts seed entries
await knex('community').insert([
{
id: 1,
name: 'main',
description: 'watercooler chat',
title: 'Main',
creator_id: 1,
category_id: 1,
actor_id: 'http://localhost:8080/c/main'
},
]);
};
// Inserts seed entries
await knex('community').insert([
{
id: 1,
name: 'main',
description: 'watercooler chat',
title: 'Main',
creator_id: 1,
category_id: 1,
actor_id: 'http://localhost:8080/c/main',
},
]);
}

26
src/database/seeds/04_post_test_data.ts

@ -1,17 +1,17 @@
import * as Knex from 'knex';
export async function seed(knex: Knex): Promise<void> {
// Deletes ALL existing entries
await knex('post').del();
// Deletes ALL existing entries
await knex('post').del();
// Inserts seed entries
await knex('post').insert([
{
id: 1,
name: 'Post Memes Here',
creator_id: 1,
community_id: 1,
ap_id: 'http://localhost:8080/post/1'
},
]);
};
// Inserts seed entries
await knex('post').insert([
{
id: 1,
name: 'Post Memes Here',
creator_id: 1,
community_id: 1,
ap_id: 'http://localhost:8080/post/1',
},
]);
}

26
src/database/seeds/05_comment_test_data.ts

@ -1,17 +1,17 @@
import * as Knex from 'knex';
export async function seed(knex: Knex): Promise<void> {
// Deletes ALL existing entries
await knex('comment').del();
// Deletes ALL existing entries
await knex('comment').del();
// Inserts seed entries
await knex('comment').insert([
{
id: 1,
creator_id: 1,
post_id: 1,
content: '_nice_',
ap_id: 'http://localhost:8080/comment/1'
},
]);
};
// Inserts seed entries
await knex('comment').insert([
{
id: 1,
creator_id: 1,
post_id: 1,
content: '_nice_',
ap_id: 'http://localhost:8080/comment/1',
},
]);
}

24
src/database/seeds/06_private-message_test_data.ts

@ -1,16 +1,16 @@
import * as Knex from 'knex';
export async function seed(knex: Knex): Promise<void> {
// Deletes ALL existing entries
await knex('private_message').del();
// Deletes ALL existing entries
await knex('private_message').del();
// Inserts seed entries
await knex('private_message').insert([
{
id: 1,
creator_id: 1,
recipient_id: 2,
content: 'hello'
},
]);
};
// Inserts seed entries
await knex('private_message').insert([
{
id: 1,
creator_id: 1,
recipient_id: 2,
content: 'hello',
},
]);
}

2
src/enums.ts

@ -6,5 +6,5 @@ export enum SortType {
TopWeek,
TopMonth,
TopYear,
TopAll
TopAll,
}

2
src/images/images.service.ts

@ -1 +1 @@
// stub for pictrs
// stub for pictrs

3
src/lib/errors.ts

@ -1,9 +1,10 @@
export class HTTPError extends Error {
code: number;
constructor(code: number, message: string) {
super(message);
this.code = code;
}
}
export const Unauthorized_Error = new HTTPError(401, 'unauthorized');
export const Unauthorized_Error = new HTTPError(401, 'unauthorized');

10
src/lib/jwt.ts

@ -15,16 +15,16 @@ export const createToken = async (claims: UserClaims): Promise<string> => {
const token: unknown = await sign({
id: claims.user_id,
token_id: claims.token_id,
iss: claims.hostname
}, 'mysecret')
iss: claims.hostname,
}, 'mysecret');
return token as string;
}
};
export const decodeToken = async (token: string): Promise<UserClaims> => {
const payload = await verify(token, 'mysecret') as { id: number, token_id: string, iss: string };
return {
user_id: payload.id,
token_id: payload.token_id,
hostname: payload.iss
hostname: payload.iss,
};
}
};

4
src/middleware/errors.middleware.ts

@ -1,9 +1,9 @@
import { Request, Response, NextFunction } from 'express';
import { HTTPError } from '../lib/errors';
export const errorHandler = async(err: HTTPError, req: Request, res: Response, next: NextFunction) => {
export const errorHandler = async (err: HTTPError, req: Request, res: Response, next: NextFunction) => {
if (err) {
res.status(err.code).json({ code: err.code, message: err.message });
}
res.status(500).json({ code: 500, message: 'unexpected error' });
}
};

6
src/middleware/user.middleware.ts

@ -9,11 +9,11 @@ export const requireAdminOrMod = async (req: Request, res: Response, next: NextF
const userId: number = parseInt(req.params.userId);
const user = await getUserById(userId);
if (user?.sitemod || user?.admin) {
next()
next();
} else {
next(Unauthorized_Error);
}
}
};
export const requireUserToken = async (req: Request, res: Response, next: NextFunction) => {
// I am pretty sure the lemmy api sends the token as auth in a query string?
@ -29,4 +29,4 @@ export const requireUserToken = async (req: Request, res: Response, next: NextFu
next(Unauthorized_Error);
}
next();
}
};

4
src/post/post.controller.ts

@ -1,6 +1,4 @@
import { Request, Response } from 'express';
import { getPostList } from './post.model';
export const getPosts = async (req: Request, res: Response) => {
return res.json({ posts: await getPostList() });
}
export const getPosts = async (req: Request, res: Response) => res.json({ posts: await getPostList() });

4
src/post/post.model.ts

@ -23,6 +23,4 @@ export interface Post {
featured: boolean;
}
export const getPostList = async (): Promise<Post[]> => {
return await knex<Post>('post');
}
export const getPostList = async (): Promise<Post[]> => await knex<Post>('post');

4
src/private-message/private-message.controller.ts

@ -1,6 +1,4 @@
import { Request, Response } from 'express';
import { getPrivateMessageList } from './private-message.model';
export const getPrivateMessages = async (req: Request, res: Response) => {
return res.json({ privateMessages: await getPrivateMessageList() });
}
export const getPrivateMessages = async (req: Request, res: Response) => res.json({ privateMessages: await getPrivateMessageList() });

4
src/private-message/private-message.model.ts

@ -13,6 +13,4 @@ export interface PrivateMessage {
local: boolean;
}
export const getPrivateMessageList = async (): Promise<PrivateMessage[]> => {
return await knex<PrivateMessage>('private_message');
}
export const getPrivateMessageList = async (): Promise<PrivateMessage[]> => await knex<PrivateMessage>('private_message');

4
src/site/site.controller.ts

@ -1,6 +1,4 @@
import { Request, Response } from 'express';
import { getSiteDetail } from './site.model';
export const getSite = async (req: Request, res: Response) => {
return res.json({ site: await getSiteDetail() });
}
export const getSite = async (req: Request, res: Response) => res.json({ site: await getSiteDetail() });

4
src/site/site.model.ts

@ -15,6 +15,4 @@ export interface Site {
banner?: string;
}
export const getSiteDetail = async (): Promise<Site|undefined> => {
return await knex<Site>('site').first();
}
export const getSiteDetail = async (): Promise<Site|undefined> => await knex<Site>('site').first();

4
src/user/models/user-ban.model.ts

@ -7,6 +7,4 @@ export interface UserBan {
published: string;
}
export const getUserBan = async (userId: number): Promise<UserBan|undefined> => {
return await knex<UserBan>('user_ban').where('user_id', userId).first();
}
export const getUserBan = async (userId: number): Promise<UserBan|undefined> => await knex<UserBan>('user_ban').where('user_id', userId).first();

4
src/user/models/user-mention.model.ts

@ -10,6 +10,4 @@ export interface UserMention {
published: string;
}
export const getUserMentions = async (userId: number): Promise<UserMention[]> => {
return await knex<UserMention>('user_mention').where('recipient_id', userId);
}
export const getUserMentions = async (userId: number): Promise<UserMention[]> => await knex<UserMention>('user_mention').where('recipient_id', userId);

4
src/user/models/user-tag.model.ts

@ -10,6 +10,4 @@ export interface UserTag {
tags: UserTags;
}
export const getUserTags = async (userId: number): Promise<UserTag|undefined> => {
return await knex<UserTag>('user_tag').where('user_id', userId).first();
}
export const getUserTags = async (userId: number): Promise<UserTag|undefined> => await knex<UserTag>('user_tag').where('user_id', userId).first();

5
src/user/models/user-token.model.ts

@ -11,7 +11,4 @@ export interface UserToken {
is_revoked: boolean;
}
export const getUserTokens = async (userId: number): Promise<UserToken[]> => {
return await knex<UserToken>('hexbear.user_tokens').where('user_id', userId);
}
export const getUserTokens = async (userId: number): Promise<UserToken[]> => await knex<UserToken>('hexbear.user_tokens').where('user_id', userId);

52
src/user/models/user.model.ts

@ -1,7 +1,7 @@
import { knex } from '../../database/knex';
import { SortType } from '../../enums';
import dayjs from 'dayjs';
import { off } from 'process';
import { knex } from '../../database/knex';
import { SortType } from '../../enums';
export interface User {
id: number;
@ -34,13 +34,9 @@ export interface User {
inbox_disabled: boolean;
}
export const getUserList = (): Promise<User[]> => {
return knex<User>('user_');
}
export const getUserList = (): Promise<User[]> => knex<User>('user_');
export const getUserById = (userId: number): Promise<User|undefined> => {
return knex<User>('user_').where('id', userId).first();
}
export const getUserById = (userId: number): Promise<User|undefined> => knex<User>('user_').where('id', userId).first();
export interface UserView {
readonly id: User['id'];
@ -68,8 +64,7 @@ export interface UserView {
}
export const getUserView = async (filter: Partial<User>, omitEmail: boolean = false, sortType?: SortType, limit?: number, offset?: number): Promise<UserView[]> => {
const users = await knex<UserView>('hexbear.user_view').modify(query => {
const users = await knex<UserView>('hexbear.user_view').modify((query) => {
query.where(filter);
switch (sortType as SortType) {
@ -80,45 +75,42 @@ export const getUserView = async (filter: Partial<User>, omitEmail: boolean = fa
query.orderBy([{ column: 'comment_score', order: 'desc' }, { column: 'published', order: 'desc' }]);
break;
case SortType.New:
query.orderBy([ { column: 'published', order: 'desc' } ]);
query.orderBy([{ column: 'published', order: 'desc' }]);
break;
case SortType.TopAll:
query.orderBy([{ column: 'comment_score', order: 'desc' } ]);
query.orderBy([{ column: 'comment_score', order: 'desc' }]);
break;
case SortType.TopYear:
query.andWhere('published', '>', dayjs().subtract(1, 'year').toISOString());
query.orderBy([{ column: 'comment_score', order: 'desc' } ]);
query.orderBy([{ column: 'comment_score', order: 'desc' }]);
break;
case SortType.TopMonth:
query.andWhere('published', '>', dayjs().subtract(1, 'month').toISOString());
query.orderBy([{ column: 'comment_score', order: 'desc' } ]);
query.orderBy([{ column: 'comment_score', order: 'desc' }]);
break;
case SortType.TopWeek:
query.andWhere('published', '>', dayjs().subtract(1, 'week').toISOString());
query.orderBy([{ column: 'comment_score', order: 'desc' } ]);
query.orderBy([{ column: 'comment_score', order: 'desc' }]);
break;
case SortType.TopDay:
query.andWhere('published', '>', dayjs().subtract(1, 'day').toISOString());
query.orderBy([{ column: 'comment_score', order: 'desc' } ]);
query.orderBy([{ column: 'comment_score', order: 'desc' }]);
break;
default:
query.orderBy([ { column: 'published', order: 'desc' } ]);
}
if (limit) {
query.limit(limit);
}
query.orderBy([{ column: 'published', order: 'desc' }]);
}
if (limit) {
query.limit(limit);
}
if (offset) {
query.offset(offset);
}
if (offset) {
query.offset(offset);
}
});
if (omitEmail) {
return users.map((u: UserView) => {
return { ...u, email: '' };
});
return users.map((u: UserView) => ({ ...u, email: '' }));
}
return users;
}
};

12
src/user/user.controller.ts

@ -6,9 +6,7 @@ import { requireAdminOrMod, requireUserToken } from '../middleware/user.middlewa
const router = Router();
router.get('/', async (req: Request, res: Response) => {
return res.json({ users: await getUserList() });
});
router.get('/', async (req: Request, res: Response) => res.json({ users: await getUserList() }));
// This just makes a token for testing for now
router.get('/login', async (req: Request, res: Response) => {
@ -16,12 +14,8 @@ router.get('/login', async (req: Request, res: Response) => {
return res.json({ jwt });
});
router.get('/auth-test', requireUserToken, async (req: Request, res: Response) => {
return res.json({ users: await getUserList() });
});
router.get('/auth-test', requireUserToken, async (req: Request, res: Response) => res.json({ users: await getUserList() }));
router.get('/:userId', requireAdminOrMod, async (req: Request, res: Response) => {
return res.json({ user: await getUserSecure(parseInt(req.params.userId)) })
});
router.get('/:userId', requireAdminOrMod, async (req: Request, res: Response) => res.json({ user: await getUserSecure(parseInt(req.params.userId)) }));
export const UserRoutes = router;

14
src/user/user.service.ts

@ -1,18 +1,12 @@
import { getUserView, UserView } from './models/user.model';
export const getSiteAdmins = (): Promise<UserView[]> => {
return getUserView({ admin: true }, true);
}
export const getSiteAdmins = (): Promise<UserView[]> => getUserView({ admin: true }, true);
export const getSiteMods = (): Promise<UserView[]> => {
return getUserView({ sitemod: true }, true);
}
export const getSiteMods = (): Promise<UserView[]> => getUserView({ sitemod: true }, true);
export const getBanned = (): Promise<UserView[]> => {
return getUserView({ banned: true }, true);
}
export const getBanned = (): Promise<UserView[]> => getUserView({ banned: true }, true);
export const getUserSecure = async (userId: UserView['id']): Promise<UserView> => {
const userList = await getUserView({ id: userId }, true);
return userList[0];
}
};
Loading…
Cancel
Save