Skip to content

Commit

Permalink
format file with prettier rules
Browse files Browse the repository at this point in the history
  • Loading branch information
janishar committed Dec 19, 2022
1 parent bcdfb9a commit 54d6b0c
Show file tree
Hide file tree
Showing 42 changed files with 541 additions and 250 deletions.
2 changes: 1 addition & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
"semi": true,
"trailingComma": "all",
"singleQuote": true,
"printWidth": 100,
"printWidth": 80,
"tabWidth": 2
}
6 changes: 5 additions & 1 deletion .templates/database/model/Sample.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,8 @@ const schema = new Schema<Sample>(
},
);

export const SampleModel = model<Sample>(DOCUMENT_NAME, schema, COLLECTION_NAME);
export const SampleModel = model<Sample>(
DOCUMENT_NAME,
schema,
COLLECTION_NAME,
);
4 changes: 3 additions & 1 deletion .templates/database/repository/SampleRepo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ async function create(sample: Sample): Promise<Sample> {

async function update(sample: Sample): Promise<Sample | null> {
sample.updatedAt = new Date();
return SampleModel.findByIdAndUpdate(sample._id, sample, { new: true }).lean().exec();
return SampleModel.findByIdAndUpdate(sample._id, sample, { new: true })
.lean()
.exec();
}

export default {
Expand Down
28 changes: 24 additions & 4 deletions addons/init-mongo.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,30 @@ function seed(dbName, user, password) {
});

db.roles.insertMany([
{ code: 'LEARNER', status: true, createdAt: new Date(), updatedAt: new Date() },
{ code: 'WRITER', status: true, createdAt: new Date(), updatedAt: new Date() },
{ code: 'EDITOR', status: true, createdAt: new Date(), updatedAt: new Date() },
{ code: 'ADMIN', status: true, createdAt: new Date(), updatedAt: new Date() },
{
code: 'LEARNER',
status: true,
createdAt: new Date(),
updatedAt: new Date(),
},
{
code: 'WRITER',
status: true,
createdAt: new Date(),
updatedAt: new Date(),
},
{
code: 'EDITOR',
status: true,
createdAt: new Date(),
updatedAt: new Date(),
},
{
code: 'ADMIN',
status: true,
createdAt: new Date(),
updatedAt: new Date(),
},
]);

db.users.insert({
Expand Down
19 changes: 15 additions & 4 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ import cors from 'cors';
import { corsUrl, environment } from './config';
import './database'; // initialize database
import './cache'; // initialize cache
import { NotFoundError, ApiError, InternalError, ErrorType } from './core/ApiError';
import {
NotFoundError,
ApiError,
InternalError,
ErrorType,
} from './core/ApiError';
import routesV1 from './routes/v1';

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

app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb', extended: true, parameterLimit: 50000 }));
app.use(
express.urlencoded({ limit: '10mb', extended: true, parameterLimit: 50000 }),
);
app.use(cors({ origin: corsUrl, optionsSuccessStatus: 200 }));

// Routes
Expand All @@ -29,9 +36,13 @@ app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
if (err instanceof ApiError) {
ApiError.handle(err, res);
if (err.type === ErrorType.INTERNAL)
Logger.error(`500 - ${err.message} - ${req.originalUrl} - ${req.method} - ${req.ip}`);
Logger.error(
`500 - ${err.message} - ${req.originalUrl} - ${req.method} - ${req.ip}`,
);
} else {
Logger.error(`500 - ${err.message} - ${req.originalUrl} - ${req.method} - ${req.ip}`);
Logger.error(
`500 - ${err.message} - ${req.originalUrl} - ${req.method} - ${req.ip}`,
);
Logger.error(err);
if (environment === 'development') {
return res.status(500).send(err);
Expand Down
3 changes: 2 additions & 1 deletion src/auth/authUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import { tokenInfo } from '../config';

export const getAccessToken = (authorization?: string) => {
if (!authorization) throw new AuthFailureError('Invalid Authorization');
if (!authorization.startsWith('Bearer ')) throw new AuthFailureError('Invalid Authorization');
if (!authorization.startsWith('Bearer '))
throw new AuthFailureError('Invalid Authorization');
return authorization.split(' ')[1];
};

Expand Down
6 changes: 5 additions & 1 deletion src/auth/authentication.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import express from 'express';
import { ProtectedRequest } from 'app-request';
import UserRepo from '../database/repository/UserRepo';
import { AuthFailureError, AccessTokenError, TokenExpiredError } from '../core/ApiError';
import {
AuthFailureError,
AccessTokenError,
TokenExpiredError,
} from '../core/ApiError';
import JWT from '../core/JWT';
import KeystoreRepo from '../database/repository/KeystoreRepo';
import { Types } from 'mongoose';
Expand Down
11 changes: 9 additions & 2 deletions src/cache/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,11 @@ export async function addToList(key: Key | DynamicKeyType, value: any) {
return await cache.rPushX(key, item);
}

export async function getListRange<T>(key: Key | DynamicKeyType, start = 0, end = -1) {
export async function getListRange<T>(
key: Key | DynamicKeyType,
start = 0,
end = -1,
) {
const type = await cache.type(key);
if (type !== TYPES.LIST) return null;

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

export async function addToOrderedSet(key: Key, items: Array<{ score: number; value: any }>) {
export async function addToOrderedSet(
key: Key,
items: Array<{ score: number; value: any }>,
) {
const type = await cache.type(key);
if (type !== TYPES.ZSET) return null;

Expand Down
6 changes: 4 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,7 @@ export const redis = {
};

export const caching = {
contentCacheDuration: parseInt(process.env.CONTENT_CACHE_DURATION_MILLIS || '600000'),
};
contentCacheDuration: parseInt(
process.env.CONTENT_CACHE_DURATION_MILLIS || '600000',
),
};
17 changes: 14 additions & 3 deletions src/core/ApiResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ abstract class ApiResponse {
return res.status(this.status).json(ApiResponse.sanitize(response));
}

public send(res: Response, headers: { [key: string]: string } = {}): Response {
public send(
res: Response,
headers: { [key: string]: string } = {},
): Response {
return this.prepare<ApiResponse>(res, this, headers);
}

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

constructor(message = 'Access token invalid') {
super(StatusCode.INVALID_ACCESS_TOKEN, ResponseStatus.UNAUTHORIZED, message);
super(
StatusCode.INVALID_ACCESS_TOKEN,
ResponseStatus.UNAUTHORIZED,
message,
);
}

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

export class TokenRefreshResponse extends ApiResponse {
constructor(message: string, private accessToken: string, private refreshToken: string) {
constructor(
message: string,
private accessToken: string,
private refreshToken: string,
) {
super(StatusCode.SUCCESS, ResponseStatus.SUCCESS, message);
}

Expand Down
22 changes: 18 additions & 4 deletions src/core/JWT.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,13 @@ export class JwtPayload {
exp: number;
prm: string;

constructor(issuer: string, audience: string, subject: string, param: string, validity: number) {
constructor(
issuer: string,
audience: string,
subject: string,
param: string,
validity: number,
) {
this.iss = issuer;
this.aud = audience;
this.sub = subject;
Expand All @@ -32,11 +38,17 @@ export class JwtPayload {
}

async function readPublicKey(): Promise<string> {
return promisify(readFile)(path.join(__dirname, '../../keys/public.pem'), 'utf8');
return promisify(readFile)(
path.join(__dirname, '../../keys/public.pem'),
'utf8',
);
}

async function readPrivateKey(): Promise<string> {
return promisify(readFile)(path.join(__dirname, '../../keys/private.pem'), 'utf8');
return promisify(readFile)(
path.join(__dirname, '../../keys/private.pem'),
'utf8',
);
}

async function encode(payload: JwtPayload): Promise<string> {
Expand Down Expand Up @@ -69,7 +81,9 @@ async function decode(token: string): Promise<JwtPayload> {
const cert = await readPublicKey();
try {
// @ts-ignore
return (await promisify(verify)(token, cert, { ignoreExpiration: true })) as JwtPayload;
return (await promisify(verify)(token, cert, {
ignoreExpiration: true,
})) as JwtPayload;
} catch (e) {
Logger.debug(e);
throw new BadTokenError();
Expand Down
10 changes: 6 additions & 4 deletions src/database/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import Logger from '../core/Logger';
import { db } from '../config';

// Build the connection string
const dbURI = `mongodb://${db.user}:${encodeURIComponent(db.password)}@${db.host}:${db.port}/${
db.name
}`;
const dbURI = `mongodb://${db.user}:${encodeURIComponent(db.password)}@${
db.host
}:${db.port}/${db.name}`;

const options = {
autoIndex: true,
Expand Down Expand Up @@ -59,7 +59,9 @@ mongoose.connection.on('disconnected', () => {
// If the Node process ends, close the Mongoose connection
process.on('SIGINT', () => {
mongoose.connection.close(() => {
Logger.info('Mongoose default connection disconnected through app termination');
Logger.info(
'Mongoose default connection disconnected through app termination',
);
process.exit(0);
});
});
Expand Down
6 changes: 5 additions & 1 deletion src/database/model/ApiKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,8 @@ const schema = new Schema<ApiKey>(

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

export const ApiKeyModel = model<ApiKey>(DOCUMENT_NAME, schema, COLLECTION_NAME);
export const ApiKeyModel = model<ApiKey>(
DOCUMENT_NAME,
schema,
COLLECTION_NAME,
);
6 changes: 5 additions & 1 deletion src/database/model/Keystore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,8 @@ schema.index({ client: 1 });
schema.index({ client: 1, primaryKey: 1, status: 1 });
schema.index({ client: 1, primaryKey: 1, secondaryKey: 1 });

export const KeystoreModel = model<Keystore>(DOCUMENT_NAME, schema, COLLECTION_NAME);
export const KeystoreModel = model<Keystore>(
DOCUMENT_NAME,
schema,
COLLECTION_NAME,
);
27 changes: 21 additions & 6 deletions src/database/repository/BlogRepo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ async function create(blog: Blog): Promise<Blog> {

async function update(blog: Blog): Promise<Blog | null> {
blog.updatedAt = new Date();
return BlogModel.findByIdAndUpdate(blog._id, blog, { new: true }).lean().exec();
return BlogModel.findByIdAndUpdate(blog._id, blog, { new: true })
.lean()
.exec();
}

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

async function findInfoForPublishedById(id: Types.ObjectId): Promise<Blog | null> {
async function findInfoForPublishedById(
id: Types.ObjectId,
): Promise<Blog | null> {
return BlogModel.findOne({ _id: id, isPublished: true, status: true })
.select('+text')
.populate('author', AUTHOR_DETAIL)
Expand All @@ -34,14 +38,20 @@ async function findInfoForPublishedById(id: Types.ObjectId): Promise<Blog | null

async function findBlogAllDataById(id: Types.ObjectId): Promise<Blog | null> {
return BlogModel.findOne({ _id: id, status: true })
.select('+text +draftText +isSubmitted +isDraft +isPublished +status +createdBy +updatedBy')
.select(
'+text +draftText +isSubmitted +isDraft +isPublished +status +createdBy +updatedBy',
)
.populate('author', AUTHOR_DETAIL)
.lean()
.exec();
}

async function findPublishedByUrl(blogUrl: string): Promise<Blog | null> {
return BlogModel.findOne({ blogUrl: blogUrl, isPublished: true, status: true })
return BlogModel.findOne({
blogUrl: blogUrl,
isPublished: true,
status: true,
})
.select('+text')
.populate('author', AUTHOR_DETAIL)
.lean()
Expand Down Expand Up @@ -98,7 +108,9 @@ async function findAllDraftsForWriter(user: User): Promise<Blog[]> {
return findDetailedBlogs({ author: user, status: true, isDraft: true });
}

async function findDetailedBlogs(query: Record<string, unknown>): Promise<Blog[]> {
async function findDetailedBlogs(
query: Record<string, unknown>,
): Promise<Blog[]> {
return BlogModel.find(query)
.select('+isSubmitted +isDraft +isPublished +createdBy +updatedBy')
.populate('author', AUTHOR_DETAIL)
Expand All @@ -109,7 +121,10 @@ async function findDetailedBlogs(query: Record<string, unknown>): Promise<Blog[]
.exec();
}

async function findLatestBlogs(pageNumber: number, limit: number): Promise<Blog[]> {
async function findLatestBlogs(
pageNumber: number,
limit: number,
): Promise<Blog[]> {
return BlogModel.find({ status: true, isPublished: true })
.skip(limit * (pageNumber - 1))
.limit(limit)
Expand Down
14 changes: 12 additions & 2 deletions src/database/repository/KeystoreRepo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ import { Types } from 'mongoose';
import User from '../model/User';

async function findforKey(client: User, key: string): Promise<Keystore | null> {
return KeystoreModel.findOne({ client: client, primaryKey: key, status: true }).lean().exec();
return KeystoreModel.findOne({
client: client,
primaryKey: key,
status: true,
})
.lean()
.exec();
}

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

async function create(client: User, primaryKey: string, secondaryKey: string): Promise<Keystore> {
async function create(
client: User,
primaryKey: string,
secondaryKey: string,
): Promise<Keystore> {
const now = new Date();
const keystore = await KeystoreModel.create({
client: client,
Expand Down
Loading

0 comments on commit 54d6b0c

Please sign in to comment.