Skip to content

Commit 54d6b0c

Browse files
committed
format file with prettier rules
1 parent bcdfb9a commit 54d6b0c

File tree

42 files changed

+541
-250
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+541
-250
lines changed

.prettierrc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,6 @@
33
"semi": true,
44
"trailingComma": "all",
55
"singleQuote": true,
6-
"printWidth": 100,
6+
"printWidth": 80,
77
"tabWidth": 2
88
}

.templates/database/model/Sample.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,8 @@ const schema = new Schema<Sample>(
4343
},
4444
);
4545

46-
export const SampleModel = model<Sample>(DOCUMENT_NAME, schema, COLLECTION_NAME);
46+
export const SampleModel = model<Sample>(
47+
DOCUMENT_NAME,
48+
schema,
49+
COLLECTION_NAME,
50+
);

.templates/database/repository/SampleRepo.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ async function create(sample: Sample): Promise<Sample> {
1515

1616
async function update(sample: Sample): Promise<Sample | null> {
1717
sample.updatedAt = new Date();
18-
return SampleModel.findByIdAndUpdate(sample._id, sample, { new: true }).lean().exec();
18+
return SampleModel.findByIdAndUpdate(sample._id, sample, { new: true })
19+
.lean()
20+
.exec();
1921
}
2022

2123
export default {

addons/init-mongo.js

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,30 @@ function seed(dbName, user, password) {
2020
});
2121

2222
db.roles.insertMany([
23-
{ code: 'LEARNER', status: true, createdAt: new Date(), updatedAt: new Date() },
24-
{ code: 'WRITER', status: true, createdAt: new Date(), updatedAt: new Date() },
25-
{ code: 'EDITOR', status: true, createdAt: new Date(), updatedAt: new Date() },
26-
{ code: 'ADMIN', status: true, createdAt: new Date(), updatedAt: new Date() },
23+
{
24+
code: 'LEARNER',
25+
status: true,
26+
createdAt: new Date(),
27+
updatedAt: new Date(),
28+
},
29+
{
30+
code: 'WRITER',
31+
status: true,
32+
createdAt: new Date(),
33+
updatedAt: new Date(),
34+
},
35+
{
36+
code: 'EDITOR',
37+
status: true,
38+
createdAt: new Date(),
39+
updatedAt: new Date(),
40+
},
41+
{
42+
code: 'ADMIN',
43+
status: true,
44+
createdAt: new Date(),
45+
updatedAt: new Date(),
46+
},
2747
]);
2848

2949
db.users.insert({

src/app.ts

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,12 @@ import cors from 'cors';
44
import { corsUrl, environment } from './config';
55
import './database'; // initialize database
66
import './cache'; // initialize cache
7-
import { NotFoundError, ApiError, InternalError, ErrorType } from './core/ApiError';
7+
import {
8+
NotFoundError,
9+
ApiError,
10+
InternalError,
11+
ErrorType,
12+
} from './core/ApiError';
813
import routesV1 from './routes/v1';
914

1015
process.on('uncaughtException', (e) => {
@@ -14,7 +19,9 @@ process.on('uncaughtException', (e) => {
1419
const app = express();
1520

1621
app.use(express.json({ limit: '10mb' }));
17-
app.use(express.urlencoded({ limit: '10mb', extended: true, parameterLimit: 50000 }));
22+
app.use(
23+
express.urlencoded({ limit: '10mb', extended: true, parameterLimit: 50000 }),
24+
);
1825
app.use(cors({ origin: corsUrl, optionsSuccessStatus: 200 }));
1926

2027
// Routes
@@ -29,9 +36,13 @@ app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
2936
if (err instanceof ApiError) {
3037
ApiError.handle(err, res);
3138
if (err.type === ErrorType.INTERNAL)
32-
Logger.error(`500 - ${err.message} - ${req.originalUrl} - ${req.method} - ${req.ip}`);
39+
Logger.error(
40+
`500 - ${err.message} - ${req.originalUrl} - ${req.method} - ${req.ip}`,
41+
);
3342
} else {
34-
Logger.error(`500 - ${err.message} - ${req.originalUrl} - ${req.method} - ${req.ip}`);
43+
Logger.error(
44+
`500 - ${err.message} - ${req.originalUrl} - ${req.method} - ${req.ip}`,
45+
);
3546
Logger.error(err);
3647
if (environment === 'development') {
3748
return res.status(500).send(err);

src/auth/authUtils.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ import { tokenInfo } from '../config';
77

88
export const getAccessToken = (authorization?: string) => {
99
if (!authorization) throw new AuthFailureError('Invalid Authorization');
10-
if (!authorization.startsWith('Bearer ')) throw new AuthFailureError('Invalid Authorization');
10+
if (!authorization.startsWith('Bearer '))
11+
throw new AuthFailureError('Invalid Authorization');
1112
return authorization.split(' ')[1];
1213
};
1314

src/auth/authentication.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
import express from 'express';
22
import { ProtectedRequest } from 'app-request';
33
import UserRepo from '../database/repository/UserRepo';
4-
import { AuthFailureError, AccessTokenError, TokenExpiredError } from '../core/ApiError';
4+
import {
5+
AuthFailureError,
6+
AccessTokenError,
7+
TokenExpiredError,
8+
} from '../core/ApiError';
59
import JWT from '../core/JWT';
610
import KeystoreRepo from '../database/repository/KeystoreRepo';
711
import { Types } from 'mongoose';

src/cache/query.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,11 @@ export async function addToList(key: Key | DynamicKeyType, value: any) {
7272
return await cache.rPushX(key, item);
7373
}
7474

75-
export async function getListRange<T>(key: Key | DynamicKeyType, start = 0, end = -1) {
75+
export async function getListRange<T>(
76+
key: Key | DynamicKeyType,
77+
start = 0,
78+
end = -1,
79+
) {
7680
const type = await cache.type(key);
7781
if (type !== TYPES.LIST) return null;
7882

@@ -98,7 +102,10 @@ export async function setOrderedSet(
98102
return await multi.exec();
99103
}
100104

101-
export async function addToOrderedSet(key: Key, items: Array<{ score: number; value: any }>) {
105+
export async function addToOrderedSet(
106+
key: Key,
107+
items: Array<{ score: number; value: any }>,
108+
) {
102109
const type = await cache.type(key);
103110
if (type !== TYPES.ZSET) return null;
104111

src/config.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,5 +31,7 @@ export const redis = {
3131
};
3232

3333
export const caching = {
34-
contentCacheDuration: parseInt(process.env.CONTENT_CACHE_DURATION_MILLIS || '600000'),
35-
};
34+
contentCacheDuration: parseInt(
35+
process.env.CONTENT_CACHE_DURATION_MILLIS || '600000',
36+
),
37+
};

src/core/ApiResponse.ts

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,10 @@ abstract class ApiResponse {
3333
return res.status(this.status).json(ApiResponse.sanitize(response));
3434
}
3535

36-
public send(res: Response, headers: { [key: string]: string } = {}): Response {
36+
public send(
37+
res: Response,
38+
headers: { [key: string]: string } = {},
39+
): Response {
3740
return this.prepare<ApiResponse>(res, this, headers);
3841
}
3942

@@ -107,7 +110,11 @@ export class AccessTokenErrorResponse extends ApiResponse {
107110
private instruction = 'refresh_token';
108111

109112
constructor(message = 'Access token invalid') {
110-
super(StatusCode.INVALID_ACCESS_TOKEN, ResponseStatus.UNAUTHORIZED, message);
113+
super(
114+
StatusCode.INVALID_ACCESS_TOKEN,
115+
ResponseStatus.UNAUTHORIZED,
116+
message,
117+
);
111118
}
112119

113120
send(res: Response, headers: { [key: string]: string } = {}): Response {
@@ -117,7 +124,11 @@ export class AccessTokenErrorResponse extends ApiResponse {
117124
}
118125

119126
export class TokenRefreshResponse extends ApiResponse {
120-
constructor(message: string, private accessToken: string, private refreshToken: string) {
127+
constructor(
128+
message: string,
129+
private accessToken: string,
130+
private refreshToken: string,
131+
) {
121132
super(StatusCode.SUCCESS, ResponseStatus.SUCCESS, message);
122133
}
123134

src/core/JWT.ts

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,13 @@ export class JwtPayload {
2121
exp: number;
2222
prm: string;
2323

24-
constructor(issuer: string, audience: string, subject: string, param: string, validity: number) {
24+
constructor(
25+
issuer: string,
26+
audience: string,
27+
subject: string,
28+
param: string,
29+
validity: number,
30+
) {
2531
this.iss = issuer;
2632
this.aud = audience;
2733
this.sub = subject;
@@ -32,11 +38,17 @@ export class JwtPayload {
3238
}
3339

3440
async function readPublicKey(): Promise<string> {
35-
return promisify(readFile)(path.join(__dirname, '../../keys/public.pem'), 'utf8');
41+
return promisify(readFile)(
42+
path.join(__dirname, '../../keys/public.pem'),
43+
'utf8',
44+
);
3645
}
3746

3847
async function readPrivateKey(): Promise<string> {
39-
return promisify(readFile)(path.join(__dirname, '../../keys/private.pem'), 'utf8');
48+
return promisify(readFile)(
49+
path.join(__dirname, '../../keys/private.pem'),
50+
'utf8',
51+
);
4052
}
4153

4254
async function encode(payload: JwtPayload): Promise<string> {
@@ -69,7 +81,9 @@ async function decode(token: string): Promise<JwtPayload> {
6981
const cert = await readPublicKey();
7082
try {
7183
// @ts-ignore
72-
return (await promisify(verify)(token, cert, { ignoreExpiration: true })) as JwtPayload;
84+
return (await promisify(verify)(token, cert, {
85+
ignoreExpiration: true,
86+
})) as JwtPayload;
7387
} catch (e) {
7488
Logger.debug(e);
7589
throw new BadTokenError();

src/database/index.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@ import Logger from '../core/Logger';
33
import { db } from '../config';
44

55
// Build the connection string
6-
const dbURI = `mongodb://${db.user}:${encodeURIComponent(db.password)}@${db.host}:${db.port}/${
7-
db.name
8-
}`;
6+
const dbURI = `mongodb://${db.user}:${encodeURIComponent(db.password)}@${
7+
db.host
8+
}:${db.port}/${db.name}`;
99

1010
const options = {
1111
autoIndex: true,
@@ -59,7 +59,9 @@ mongoose.connection.on('disconnected', () => {
5959
// If the Node process ends, close the Mongoose connection
6060
process.on('SIGINT', () => {
6161
mongoose.connection.close(() => {
62-
Logger.info('Mongoose default connection disconnected through app termination');
62+
Logger.info(
63+
'Mongoose default connection disconnected through app termination',
64+
);
6365
process.exit(0);
6466
});
6567
});

src/database/model/ApiKey.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,4 +76,8 @@ const schema = new Schema<ApiKey>(
7676

7777
schema.index({ key: 1, status: 1 });
7878

79-
export const ApiKeyModel = model<ApiKey>(DOCUMENT_NAME, schema, COLLECTION_NAME);
79+
export const ApiKeyModel = model<ApiKey>(
80+
DOCUMENT_NAME,
81+
schema,
82+
COLLECTION_NAME,
83+
);

src/database/model/Keystore.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,8 @@ schema.index({ client: 1 });
5555
schema.index({ client: 1, primaryKey: 1, status: 1 });
5656
schema.index({ client: 1, primaryKey: 1, secondaryKey: 1 });
5757

58-
export const KeystoreModel = model<Keystore>(DOCUMENT_NAME, schema, COLLECTION_NAME);
58+
export const KeystoreModel = model<Keystore>(
59+
DOCUMENT_NAME,
60+
schema,
61+
COLLECTION_NAME,
62+
);

src/database/repository/BlogRepo.ts

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@ async function create(blog: Blog): Promise<Blog> {
1414

1515
async function update(blog: Blog): Promise<Blog | null> {
1616
blog.updatedAt = new Date();
17-
return BlogModel.findByIdAndUpdate(blog._id, blog, { new: true }).lean().exec();
17+
return BlogModel.findByIdAndUpdate(blog._id, blog, { new: true })
18+
.lean()
19+
.exec();
1820
}
1921

2022
async function findInfoById(id: Types.ObjectId): Promise<Blog | null> {
@@ -24,7 +26,9 @@ async function findInfoById(id: Types.ObjectId): Promise<Blog | null> {
2426
.exec();
2527
}
2628

27-
async function findInfoForPublishedById(id: Types.ObjectId): Promise<Blog | null> {
29+
async function findInfoForPublishedById(
30+
id: Types.ObjectId,
31+
): Promise<Blog | null> {
2832
return BlogModel.findOne({ _id: id, isPublished: true, status: true })
2933
.select('+text')
3034
.populate('author', AUTHOR_DETAIL)
@@ -34,14 +38,20 @@ async function findInfoForPublishedById(id: Types.ObjectId): Promise<Blog | null
3438

3539
async function findBlogAllDataById(id: Types.ObjectId): Promise<Blog | null> {
3640
return BlogModel.findOne({ _id: id, status: true })
37-
.select('+text +draftText +isSubmitted +isDraft +isPublished +status +createdBy +updatedBy')
41+
.select(
42+
'+text +draftText +isSubmitted +isDraft +isPublished +status +createdBy +updatedBy',
43+
)
3844
.populate('author', AUTHOR_DETAIL)
3945
.lean()
4046
.exec();
4147
}
4248

4349
async function findPublishedByUrl(blogUrl: string): Promise<Blog | null> {
44-
return BlogModel.findOne({ blogUrl: blogUrl, isPublished: true, status: true })
50+
return BlogModel.findOne({
51+
blogUrl: blogUrl,
52+
isPublished: true,
53+
status: true,
54+
})
4555
.select('+text')
4656
.populate('author', AUTHOR_DETAIL)
4757
.lean()
@@ -98,7 +108,9 @@ async function findAllDraftsForWriter(user: User): Promise<Blog[]> {
98108
return findDetailedBlogs({ author: user, status: true, isDraft: true });
99109
}
100110

101-
async function findDetailedBlogs(query: Record<string, unknown>): Promise<Blog[]> {
111+
async function findDetailedBlogs(
112+
query: Record<string, unknown>,
113+
): Promise<Blog[]> {
102114
return BlogModel.find(query)
103115
.select('+isSubmitted +isDraft +isPublished +createdBy +updatedBy')
104116
.populate('author', AUTHOR_DETAIL)
@@ -109,7 +121,10 @@ async function findDetailedBlogs(query: Record<string, unknown>): Promise<Blog[]
109121
.exec();
110122
}
111123

112-
async function findLatestBlogs(pageNumber: number, limit: number): Promise<Blog[]> {
124+
async function findLatestBlogs(
125+
pageNumber: number,
126+
limit: number,
127+
): Promise<Blog[]> {
113128
return BlogModel.find({ status: true, isPublished: true })
114129
.skip(limit * (pageNumber - 1))
115130
.limit(limit)

src/database/repository/KeystoreRepo.ts

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,13 @@ import { Types } from 'mongoose';
33
import User from '../model/User';
44

55
async function findforKey(client: User, key: string): Promise<Keystore | null> {
6-
return KeystoreModel.findOne({ client: client, primaryKey: key, status: true }).lean().exec();
6+
return KeystoreModel.findOne({
7+
client: client,
8+
primaryKey: key,
9+
status: true,
10+
})
11+
.lean()
12+
.exec();
713
}
814

915
async function remove(id: Types.ObjectId): Promise<Keystore | null> {
@@ -28,7 +34,11 @@ async function find(
2834
.exec();
2935
}
3036

31-
async function create(client: User, primaryKey: string, secondaryKey: string): Promise<Keystore> {
37+
async function create(
38+
client: User,
39+
primaryKey: string,
40+
secondaryKey: string,
41+
): Promise<Keystore> {
3242
const now = new Date();
3343
const keystore = await KeystoreModel.create({
3444
client: client,

0 commit comments

Comments
 (0)