diff --git a/src/auth/authUtils.ts b/src/auth/authUtils.ts index fbe2b70..9af20a6 100755 --- a/src/auth/authUtils.ts +++ b/src/auth/authUtils.ts @@ -2,7 +2,7 @@ import { Tokens } from 'app-request'; import { AuthFailureError, InternalError } from '../core/ApiError'; import JWT, { JwtPayload } from '../core/JWT'; import { Types } from 'mongoose'; -import { IUser } from '../database/model/User'; +import User from '../database/model/User'; import { tokenInfo } from '../config'; export const validateTokenData = async (payload: JwtPayload, userId: Types.ObjectId): Promise => { @@ -14,7 +14,7 @@ export const validateTokenData = async (payload: JwtPayload, userId: Types.Objec return payload; }; -export const createTokens = async (user: IUser, accessTokenKey: string, refreshTokenKey: string) +export const createTokens = async (user: User, accessTokenKey: string, refreshTokenKey: string) : Promise => { const accessToken = await JWT.encode( new JwtPayload( diff --git a/src/database/model/ApiKey.ts b/src/database/model/ApiKey.ts index c4948d3..e05a02e 100755 --- a/src/database/model/ApiKey.ts +++ b/src/database/model/ApiKey.ts @@ -3,7 +3,7 @@ import { Schema, model, Document, Types } from 'mongoose'; export const DOCUMENT_NAME = 'ApiKey'; export const COLLECTION_NAME = 'api_keys'; -export interface IApiKey extends Document { +export default interface ApiKey extends Document { key: string; version: number; metadata: string; @@ -49,6 +49,4 @@ const schema = new Schema( versionKey: false }); -const ApiKey = model(DOCUMENT_NAME, schema, COLLECTION_NAME); - -export default ApiKey; \ No newline at end of file +export const ApiKeyModel = model(DOCUMENT_NAME, schema, COLLECTION_NAME); \ No newline at end of file diff --git a/src/database/model/Blog.ts b/src/database/model/Blog.ts index 3939cf9..b3c2eb2 100755 --- a/src/database/model/Blog.ts +++ b/src/database/model/Blog.ts @@ -1,17 +1,16 @@ import { Schema, model, Document } from 'mongoose'; -import { IUser } from './User'; -import Logger from '../../core/Logger'; +import User from './User'; export const DOCUMENT_NAME = 'Blog'; export const COLLECTION_NAME = 'blogs'; -export interface IBlog extends Document { +export default interface Blog extends Document { title: string; description: string; text?: string; draftText: string; tags: string[]; - author: IUser; + author: User; imgUrl?: string; blogUrl: string; likes?: number; @@ -21,8 +20,8 @@ export interface IBlog extends Document { isPublished: boolean; status?: boolean; publishedAt?: Date; - createdBy?: IUser; - updatedBy?: IUser; + createdBy?: User; + updatedBy?: User; createdAt?: Date; updatedAt?: Date; } @@ -145,6 +144,4 @@ const schema = new Schema( { weights: { title: 3, description: 1 }, background: false } ); -const Blog = model(DOCUMENT_NAME, schema, COLLECTION_NAME); - -export default Blog; \ No newline at end of file +export const BlogModel = model(DOCUMENT_NAME, schema, COLLECTION_NAME); \ No newline at end of file diff --git a/src/database/model/Keystore.ts b/src/database/model/Keystore.ts index 8cb7bbe..0b15a1e 100755 --- a/src/database/model/Keystore.ts +++ b/src/database/model/Keystore.ts @@ -1,11 +1,11 @@ import { Schema, model, Document } from 'mongoose'; -import { IUser } from './User'; +import User from './User'; export const DOCUMENT_NAME = 'Keystore'; export const COLLECTION_NAME = 'keystores'; -export interface IKeystore extends Document { - client: IUser; +export default interface Keystore extends Document { + client: User; primaryKey: string; secondaryKey: string; status?: boolean; @@ -50,6 +50,4 @@ const schema = new Schema( versionKey: false }); -const Keystore = model(DOCUMENT_NAME, schema, COLLECTION_NAME); - -export default Keystore; \ No newline at end of file +export const KeystoreModel = model(DOCUMENT_NAME, schema, COLLECTION_NAME); \ No newline at end of file diff --git a/src/database/model/Role.ts b/src/database/model/Role.ts index 3239861..304a4ed 100755 --- a/src/database/model/Role.ts +++ b/src/database/model/Role.ts @@ -10,7 +10,7 @@ export const enum RoleCode { ADMIN = 'ADMIN', } -export interface IRole extends Document { +export default interface Role extends Document { code: string; status?: boolean; createdAt?: Date; @@ -48,6 +48,4 @@ const schema = new Schema( versionKey: false }); -const Role = model(DOCUMENT_NAME, schema, COLLECTION_NAME); - -export default Role; \ No newline at end of file +export const RoleModel = model(DOCUMENT_NAME, schema, COLLECTION_NAME); \ No newline at end of file diff --git a/src/database/model/User.ts b/src/database/model/User.ts index 39f333c..cb6de9f 100755 --- a/src/database/model/User.ts +++ b/src/database/model/User.ts @@ -1,15 +1,15 @@ import { model, Schema, Document, Types } from 'mongoose'; -import { IRole } from './Role'; +import Role from './Role'; export const DOCUMENT_NAME = 'User'; export const COLLECTION_NAME = 'users'; -export interface IUser extends Document { +export default interface User extends Document { name: string; email?: string; password?: string; profilePicUrl?: string; - roles: IRole[]; + roles: Role[]; verified?: boolean; status?: boolean; createdAt?: Date; @@ -70,6 +70,4 @@ const schema = new Schema( versionKey: false }); -const User = model(DOCUMENT_NAME, schema, COLLECTION_NAME); - -export default User; \ No newline at end of file +export const UserModel = model(DOCUMENT_NAME, schema, COLLECTION_NAME); \ No newline at end of file diff --git a/src/database/repository/ApiKeyRepo.ts b/src/database/repository/ApiKeyRepo.ts index 89833b9..67e3924 100755 --- a/src/database/repository/ApiKeyRepo.ts +++ b/src/database/repository/ApiKeyRepo.ts @@ -1,8 +1,8 @@ -import ApiKey, { IApiKey } from '../model/ApiKey'; +import ApiKey, { ApiKeyModel } from '../model/ApiKey'; export default class ApiRepo { - public static async findByKey(key: string): Promise { - return ApiKey.findOne({ key: key, status: true }).lean().exec(); + public static async findByKey(key: string): Promise { + return ApiKeyModel.findOne({ key: key, status: true }).lean().exec(); } } \ No newline at end of file diff --git a/src/database/repository/BlogRepo.ts b/src/database/repository/BlogRepo.ts index 0be7254..3e26329 100755 --- a/src/database/repository/BlogRepo.ts +++ b/src/database/repository/BlogRepo.ts @@ -1,6 +1,6 @@ -import Blog, { IBlog } from '../model/Blog'; +import Blog, { BlogModel } from '../model/Blog'; import { Types } from 'mongoose'; -import { IUser } from '../model/User'; +import User from '../model/User'; export default class BlogRepo { @@ -8,128 +8,128 @@ export default class BlogRepo { private static BLOG_INFO_ADDITIONAL = '+isSubmitted +isDraft +isPublished +createdBy +updatedBy'; private static BLOG_ALL_DATA = '+text +draftText +isSubmitted +isDraft +isPublished +status +createdBy +updatedBy'; - public static async create(blog: IBlog): Promise { + public static async create(blog: Blog): Promise { const now = new Date(); blog.createdAt = now; blog.updatedAt = now; - const createdBlog = await Blog.create(blog); + const createdBlog = await BlogModel.create(blog); return createdBlog.toObject(); } - public static update(blog: IBlog): Promise { + public static update(blog: Blog): Promise { blog.updatedAt = new Date(); - return Blog.updateOne({ _id: blog._id }, { $set: { ...blog } }).lean().exec(); + return BlogModel.updateOne({ _id: blog._id }, { $set: { ...blog } }).lean().exec(); } - public static findInfoById(id: Types.ObjectId): Promise { - return Blog.findOne({ _id: id, status: true }) + public static findInfoById(id: Types.ObjectId): Promise { + return BlogModel.findOne({ _id: id, status: true }) .populate('author', this.AUTHOR_DETAIL) - .lean() + .lean() .exec(); } - public static findInfoWithTextById(id: Types.ObjectId): Promise { - return Blog.findOne({ _id: id, status: true }) + public static findInfoWithTextById(id: Types.ObjectId): Promise { + return BlogModel.findOne({ _id: id, status: true }) .select('+text') .populate('author', this.AUTHOR_DETAIL) - .lean() + .lean() .exec(); } - public static findInfoWithTextAndDraftTextById(id: Types.ObjectId): Promise { - return Blog.findOne({ _id: id, status: true }) + public static findInfoWithTextAndDraftTextById(id: Types.ObjectId): Promise { + return BlogModel.findOne({ _id: id, status: true }) .select('+text +draftText +isSubmitted +isDraft +isPublished +status') .populate('author', this.AUTHOR_DETAIL) - .lean() + .lean() .exec(); } - public static findBlogAllDataById(id: Types.ObjectId): Promise { - return Blog.findOne({ _id: id, status: true }) + public static findBlogAllDataById(id: Types.ObjectId): Promise { + return BlogModel.findOne({ _id: id, status: true }) .select(this.BLOG_ALL_DATA) .populate('author', this.AUTHOR_DETAIL) - .lean() + .lean() .exec(); } - public static findByUrl(blogUrl: string): Promise { - return Blog.findOne({ blogUrl: blogUrl, status: true }) + public static findByUrl(blogUrl: string): Promise { + return BlogModel.findOne({ blogUrl: blogUrl, status: true }) .select('+text') .populate('author', this.AUTHOR_DETAIL) - .lean() + .lean() .exec(); } - public static findUrlIfExists(blogUrl: string): Promise { - return Blog.findOne({ blogUrl: blogUrl }).lean().exec(); + public static findUrlIfExists(blogUrl: string): Promise { + return BlogModel.findOne({ blogUrl: blogUrl }).lean().exec(); } - public static findByTagAndPaginated(tag: string, pageNumber: number, limit: number): Promise { - return Blog.find({ tags: tag, status: true, isPublished: true }) + public static findByTagAndPaginated(tag: string, pageNumber: number, limit: number): Promise { + return BlogModel.find({ tags: tag, status: true, isPublished: true }) .skip(limit * (pageNumber - 1)) .limit(limit) .populate('author', this.AUTHOR_DETAIL) .sort({ updatedAt: -1 }) - .lean() + .lean() .exec(); } - public static findAllPublishedForAuthor(user: IUser): Promise { - return Blog.find({ author: user, status: true, isPublished: true }) + public static findAllPublishedForAuthor(user: User): Promise { + return BlogModel.find({ author: user, status: true, isPublished: true }) .populate('author', this.AUTHOR_DETAIL) .sort({ updatedAt: -1 }) - .lean() + .lean() .exec(); } - public static findAllDrafts(): Promise { + public static findAllDrafts(): Promise { return this.findDetailedBlogs({ isDraft: true, status: true }); } - public static findAllSubmissions(): Promise { + public static findAllSubmissions(): Promise { return this.findDetailedBlogs({ isSubmitted: true, status: true }); } - public static findAllPublished(): Promise { + public static findAllPublished(): Promise { return this.findDetailedBlogs({ isPublished: true, status: true }); } - public static findAllSubmissionsForWriter(user: IUser): Promise { + public static findAllSubmissionsForWriter(user: User): Promise { return this.findDetailedBlogs({ author: user, status: true, isSubmitted: true }); } - public static findAllPublishedForWriter(user: IUser): Promise { + public static findAllPublishedForWriter(user: User): Promise { return this.findDetailedBlogs({ author: user, status: true, isPublished: true }); } - public static findAllDraftsForWriter(user: IUser): Promise { + public static findAllDraftsForWriter(user: User): Promise { return this.findDetailedBlogs({ author: user, status: true, isDraft: true }); } - private static findDetailedBlogs(query: Object): Promise { - return Blog.find(query) + private static findDetailedBlogs(query: Object): Promise { + return BlogModel.find(query) .select(this.BLOG_INFO_ADDITIONAL) .populate('author', this.AUTHOR_DETAIL) .populate('createdBy', this.AUTHOR_DETAIL) .populate('updatedBy', this.AUTHOR_DETAIL) .sort({ updatedAt: -1 }) - .lean() + .lean() .exec(); } - public static findLatestBlogs(pageNumber: number, limit: number): Promise { - return Blog.find({ status: true, isPublished: true }) + public static findLatestBlogs(pageNumber: number, limit: number): Promise { + return BlogModel.find({ status: true, isPublished: true }) .skip(limit * (pageNumber - 1)) .limit(limit) .populate('author', this.AUTHOR_DETAIL) .sort({ publishedAt: -1 }) - .lean() + .lean() .exec(); } - public static searchSimilarBlogs(blog: IBlog, limit: number) - : Promise { - return Blog.find( + public static searchSimilarBlogs(blog: Blog, limit: number) + : Promise { + return BlogModel.find( { $text: { $search: blog.title, $caseSensitive: false }, status: true, @@ -143,12 +143,12 @@ export default class BlogRepo { .sort({ updatedAt: -1 }) .limit(limit) .sort({ similarity: { $meta: 'textScore' } }) - .lean() + .lean() .exec(); } - public static search(query: string, limit: number): Promise { - return Blog.find( + public static search(query: string, limit: number): Promise { + return BlogModel.find( { $text: { $search: query, $caseSensitive: false }, status: true, @@ -160,12 +160,12 @@ export default class BlogRepo { .select('-status -description') .limit(limit) .sort({ similarity: { $meta: 'textScore' } }) - .lean() + .lean() .exec(); } - public static searchLike(query: string, limit: number): Promise { - return Blog.find( + public static searchLike(query: string, limit: number): Promise { + return BlogModel.find( { title: { $regex: `.*${query}.*`, $options: 'i' }, status: true, @@ -174,7 +174,7 @@ export default class BlogRepo { .select('-status -description') .limit(limit) .sort({ score: -1 }) - .lean() + .lean() .exec(); } } \ No newline at end of file diff --git a/src/database/repository/KeystoreRepo.ts b/src/database/repository/KeystoreRepo.ts index 5c8e05c..c1c414e 100755 --- a/src/database/repository/KeystoreRepo.ts +++ b/src/database/repository/KeystoreRepo.ts @@ -1,28 +1,28 @@ -import Keystore, { IKeystore } from '../model/Keystore'; +import Keystore, { KeystoreModel } from '../model/Keystore'; import { Types } from 'mongoose'; -import { IUser } from '../model/User'; +import User from '../model/User'; export default class KeystoreRepo { - public static findforKey(client: IUser, key: string): Promise { - return Keystore.findOne({ client: client, primaryKey: key, status: true }).exec(); + public static findforKey(client: User, key: string): Promise { + return KeystoreModel.findOne({ client: client, primaryKey: key, status: true }).exec(); } - public static remove(id: Types.ObjectId): Promise { - return Keystore.findByIdAndRemove(id).lean().exec(); + public static remove(id: Types.ObjectId): Promise { + return KeystoreModel.findByIdAndRemove(id).lean().exec(); } - public static find(client: IUser, primaryKey: string, secondaryKey: string): Promise { - return Keystore + public static find(client: User, primaryKey: string, secondaryKey: string): Promise { + return KeystoreModel .findOne({ client: client, primaryKey: primaryKey, secondaryKey: secondaryKey }) - .lean() + .lean() .exec(); } - public static async create(client: IUser, primaryKey: string, secondaryKey: string) - : Promise { + public static async create(client: User, primaryKey: string, secondaryKey: string) + : Promise { const now = new Date(); - const keystore = await Keystore.create({ + const keystore = await KeystoreModel.create({ client: client, primaryKey: primaryKey, secondaryKey: secondaryKey, diff --git a/src/database/repository/RoleRepo.ts b/src/database/repository/RoleRepo.ts index bdf584e..3d039c6 100755 --- a/src/database/repository/RoleRepo.ts +++ b/src/database/repository/RoleRepo.ts @@ -1,8 +1,8 @@ -import Role, { IRole } from '../model/Role'; +import Role, { RoleModel } from '../model/Role'; export default class RoleRepo { - public static findByCode(code: string): Promise { - return Role.findOne({ code: code, status: true }).lean().exec(); + public static findByCode(code: string): Promise { + return RoleModel.findOne({ code: code, status: true }).lean().exec(); } } \ No newline at end of file diff --git a/src/database/repository/UserRepo.ts b/src/database/repository/UserRepo.ts index 0765972..c9db51b 100755 --- a/src/database/repository/UserRepo.ts +++ b/src/database/repository/UserRepo.ts @@ -1,76 +1,76 @@ -import User, { IUser } from '../model/User'; -import Role, { IRole } from '../model/Role'; +import User, { UserModel } from '../model/User'; +import Role, { RoleModel } from '../model/Role'; import { InternalError } from '../../core/ApiError'; import { Types } from 'mongoose'; import KeystoreRepo from './KeystoreRepo'; -import { IKeystore } from '../model/Keystore'; +import Keystore from '../model/Keystore'; export default class UserRepo { // contains critical information of the user - public static findById(id: Types.ObjectId): Promise { - return User.findOne({ _id: id, status: true }) + public static findById(id: Types.ObjectId): Promise { + return UserModel.findOne({ _id: id, status: true }) .select('+email +password +roles') .populate({ path: 'roles', match: { status: true } }) - .lean() + .lean() .exec(); } - public static findByEmail(email: string): Promise { - return User.findOne({ email: email, status: true }) + public static findByEmail(email: string): Promise { + return UserModel.findOne({ email: email, status: true }) .select('+email +password +roles') .populate({ path: 'roles', match: { status: true }, select: { code: 1 } }) - .lean() + .lean() .exec(); } - public static findProfileById(id: Types.ObjectId): Promise { - return User.findOne({ _id: id, status: true }) + public static findProfileById(id: Types.ObjectId): Promise { + return UserModel.findOne({ _id: id, status: true }) .select('+roles') .populate({ path: 'roles', match: { status: true }, select: { code: 1 } }) - .lean() + .lean() .exec(); } - public static findPublicProfileById(id: Types.ObjectId): Promise { - return User.findOne({ _id: id, status: true }).lean().exec(); + public static findPublicProfileById(id: Types.ObjectId): Promise { + return UserModel.findOne({ _id: id, status: true }).lean().exec(); } - public static async create(user: IUser, accessTokenKey: string, refreshTokenKey: string, roleCode: string) - : Promise<{ user: IUser, keystore: IKeystore }> { + public static async create(user: User, accessTokenKey: string, refreshTokenKey: string, roleCode: string) + : Promise<{ user: User, keystore: Keystore }> { const now = new Date(); - const role = await Role.findOne({ code: roleCode }).select('+email +password').lean().exec(); + const role = await RoleModel.findOne({ code: roleCode }).select('+email +password').lean().exec(); if (!role) throw new InternalError('Role must be defined'); user.roles = [role._id]; user.createdAt = user.updatedAt = now; - const createdUser = await User.create(user); + const createdUser = await UserModel.create(user); const keystore = await KeystoreRepo.create(createdUser._id, accessTokenKey, refreshTokenKey); return { user: createdUser.toObject(), keystore: keystore }; } - public static async update(user: IUser, accessTokenKey: string, refreshTokenKey: string) - : Promise<{ user: IUser, keystore: IKeystore }> { + public static async update(user: User, accessTokenKey: string, refreshTokenKey: string) + : Promise<{ user: User, keystore: Keystore }> { user.updatedAt = new Date(); - const result = await User.updateOne({ _id: user._id }, { $set: { ...user }, }).lean().exec(); + const result = await UserModel.updateOne({ _id: user._id }, { $set: { ...user }, }).lean().exec(); const keystore = await KeystoreRepo.create(user._id, accessTokenKey, refreshTokenKey); return { user: user, keystore: keystore }; } - public static updateInfo(user: IUser): Promise { + public static updateInfo(user: User): Promise { user.updatedAt = new Date(); - return User.updateOne({ _id: user._id }, { $set: { ...user }, }).lean().exec(); + return UserModel.updateOne({ _id: user._id }, { $set: { ...user }, }).lean().exec(); } } \ No newline at end of file diff --git a/src/routes/v1/access/signup.ts b/src/routes/v1/access/signup.ts index 55a22ca..7a53e22 100644 --- a/src/routes/v1/access/signup.ts +++ b/src/routes/v1/access/signup.ts @@ -4,7 +4,7 @@ import { RoleRequest } from 'app-request'; import crypto from 'crypto'; import UserRepo from '../../../database/repository/UserRepo'; import { BadRequestError } from '../../../core/ApiError'; -import { IUser } from '../../../database/model/User'; +import User from '../../../database/model/User'; import { createTokens } from '../../../auth/authUtils'; import validator from '../../../helpers/validator'; import schema from './schema'; @@ -24,7 +24,7 @@ router.post('/basic', validator(schema.signup), const refreshTokenKey = crypto.randomBytes(64).toString('hex'); const passwordHash = await bcrypt.hash(req.body.password, 10); - const { user: createdUser, keystore } = await UserRepo.create({ + const { user: createdUser, keystore } = await UserRepo.create({ name: req.body.name, email: req.body.email, profilePicUrl: req.body.profilePicUrl, diff --git a/src/routes/v1/blog/blogList.ts b/src/routes/v1/blog/blogList.ts index 0585738..ca268ff 100644 --- a/src/routes/v1/blog/blogList.ts +++ b/src/routes/v1/blog/blogList.ts @@ -6,7 +6,7 @@ import { Types } from 'mongoose'; import validator, { ValidationSource } from '../../../helpers/validator'; import schema from './schema'; import asyncHandler from '../../../helpers/asyncHandler'; -import { IUser } from '../../../database/model/User'; +import User from '../../../database/model/User'; const router = express.Router(); @@ -27,7 +27,7 @@ router.get('/tag/:tag', router.get('/author/id/:id', validator(schema.authorId, ValidationSource.PARAM), asyncHandler(async (req, res, next) => { - const blogs = await BlogRepo.findAllPublishedForAuthor({ + const blogs = await BlogRepo.findAllPublishedForAuthor({ _id: new Types.ObjectId(req.params.id) }); diff --git a/src/routes/v1/blog/writer.ts b/src/routes/v1/blog/writer.ts index d094b17..1c4d7e1 100755 --- a/src/routes/v1/blog/writer.ts +++ b/src/routes/v1/blog/writer.ts @@ -3,7 +3,7 @@ import { SuccessResponse, SuccessMsgResponse } from '../../../core/ApiResponse' import { ProtectedRequest, RoleRequest } from 'app-request'; import { BadRequestError, ForbiddenError } from '../../../core/ApiError'; import BlogRepo from '../../../database/repository/BlogRepo'; -import { IBlog } from '../../../database/model/Blog'; +import Blog from '../../../database/model/Blog'; import { RoleCode } from '../../../database/model/Role'; import { Types } from 'mongoose'; import validator, { ValidationSource } from '../../../helpers/validator'; @@ -30,7 +30,7 @@ router.post('/', validator(schema.blogCreate), const blog = await BlogRepo.findUrlIfExists(req.body.blogUrl); if (blog) throw new BadRequestError('Blog with this url already exists'); - const createdBlog = await BlogRepo.create({ + const createdBlog = await BlogRepo.create({ title: req.body.title, description: req.body.description, draftText: req.body.text, diff --git a/src/types/app-request.d.ts b/src/types/app-request.d.ts index 6db4911..81b23f6 100755 --- a/src/types/app-request.d.ts +++ b/src/types/app-request.d.ts @@ -1,6 +1,6 @@ import { Request } from 'express'; -import { IUser } from '../database/model/User'; -import { IKeystore } from '../database/model/Keystore'; +import User from '../database/model/User'; +import Keystore from '../database/model/Keystore'; declare interface PublicRequest extends Request { apiKey: string; @@ -11,9 +11,9 @@ declare interface RoleRequest extends PublicRequest { } declare interface ProtectedRequest extends RoleRequest { - user: IUser; + user: User; accessToken: string; - keystore: IKeystore; + keystore: Keystore; } declare interface Tokens { diff --git a/tests/auth/apikey/mock.ts b/tests/auth/apikey/mock.ts index 2c3248c..59a4c29 100644 --- a/tests/auth/apikey/mock.ts +++ b/tests/auth/apikey/mock.ts @@ -1,9 +1,9 @@ -import { IApiKey } from '../../../src/database/model/ApiKey'; +import ApiKey from '../../../src/database/model/ApiKey'; export const API_KEY = 'abc'; export const mockFindApiKey = jest.fn(async (key: string) => { - if (key == API_KEY) return { key: API_KEY }; + if (key == API_KEY) return { key: API_KEY }; else return null; }); diff --git a/tests/auth/authUtils/unit.test.ts b/tests/auth/authUtils/unit.test.ts index d85bbe3..53f8c27 100644 --- a/tests/auth/authUtils/unit.test.ts +++ b/tests/auth/authUtils/unit.test.ts @@ -4,7 +4,7 @@ import { JwtPayload } from '../../../src/core/JWT'; import { tokenInfo } from '../../../src/config'; import { Types } from 'mongoose'; import { AuthFailureError } from '../../../src/core/ApiError'; -import { IUser } from '../../../src/database/model/User'; +import User from '../../../src/database/model/User'; describe('authUtils validateTokenData tests', () => { @@ -79,7 +79,7 @@ describe('authUtils createTokens function', () => { const userId = new Types.ObjectId('553f8a4286f5c759f36f8e5b'); // Random Key - const tokens = await createTokens({ _id: userId }, ACCESS_TOKEN_KEY, REFRESH_TOKEN_KEY); + const tokens = await createTokens({ _id: userId }, ACCESS_TOKEN_KEY, REFRESH_TOKEN_KEY); expect(tokens).toHaveProperty('accessToken'); expect(tokens).toHaveProperty('refreshToken'); diff --git a/tests/auth/authentication/mock.ts b/tests/auth/authentication/mock.ts index 3b4a5ce..dbb474e 100644 --- a/tests/auth/authentication/mock.ts +++ b/tests/auth/authentication/mock.ts @@ -1,18 +1,18 @@ - // all dependent mock should be on the top +// all dependent mock should be on the top import { API_KEY } from '../apikey/mock'; -import { IUser } from '../../../src/database/model/User'; +import User from '../../../src/database/model/User'; import { Types } from 'mongoose'; import JWT, { ValidationParams, JwtPayload } from '../../../src/core/JWT'; import { BadTokenError } from '../../../src/core/ApiError'; -import { IKeystore } from '../../../src/database/model/Keystore'; +import Keystore from '../../../src/database/model/Keystore'; export const ACCESS_TOKEN = 'xyz'; export const USER_ID = new Types.ObjectId(); // random id with object id format export const mockUserFindById = jest.fn(async (id: Types.ObjectId) => { - if (USER_ID.equals(id)) return { _id: new Types.ObjectId(id) }; + if (USER_ID.equals(id)) return { _id: new Types.ObjectId(id) }; else return null; }); @@ -23,7 +23,7 @@ export const mockJwtValidate = jest.fn( }); export const mockKeystoreFindForKey = jest.fn( - async (client: IUser, key: string): Promise => ({ client: client, primaryKey: key })); + async (client: User, key: string): Promise => ({ client: client, primaryKey: key })); export const mockValidateTokenData = jest.fn(async (payload: JwtPayload, userId: Types.ObjectId): Promise => payload); diff --git a/tests/auth/authorization/mock.ts b/tests/auth/authorization/mock.ts index bbda0e6..212068f 100644 --- a/tests/auth/authorization/mock.ts +++ b/tests/auth/authorization/mock.ts @@ -2,8 +2,8 @@ import { USER_ID } from '../authentication/mock'; import { Types } from 'mongoose'; -import { IUser } from '../../../src/database/model/User'; -import { RoleCode, IRole } from '../../../src/database/model/Role'; +import User from '../../../src/database/model/User'; +import Role, { RoleCode } from '../../../src/database/model/Role'; export const LEARNER_ROLE_ID = new Types.ObjectId(); // random id @@ -14,43 +14,43 @@ export const USER_ID_WRITER = new Types.ObjectId(); // random id export const USER_ID_EDITOR = new Types.ObjectId(); // random id export const mockUserFindById = jest.fn(async (id: Types.ObjectId) => { - if (USER_ID.equals(id)) return { + if (USER_ID.equals(id)) return { _id: USER_ID, roles: [ - { _id: LEARNER_ROLE_ID, code: RoleCode.LEARNER }, + { _id: LEARNER_ROLE_ID, code: RoleCode.LEARNER }, ] }; - if (USER_ID_WRITER.equals(id)) return { + if (USER_ID_WRITER.equals(id)) return { _id: USER_ID_WRITER, roles: [ - { _id: LEARNER_ROLE_ID, code: RoleCode.LEARNER }, - { _id: WRITER_ROLE_ID, code: RoleCode.WRITER }, + { _id: LEARNER_ROLE_ID, code: RoleCode.LEARNER }, + { _id: WRITER_ROLE_ID, code: RoleCode.WRITER }, ] }; - if (USER_ID_EDITOR.equals(id)) return { + if (USER_ID_EDITOR.equals(id)) return { _id: USER_ID_EDITOR, roles: [ - { _id: LEARNER_ROLE_ID, code: RoleCode.LEARNER }, - { _id: WRITER_ROLE_ID, code: RoleCode.EDITOR }, + { _id: LEARNER_ROLE_ID, code: RoleCode.LEARNER }, + { _id: WRITER_ROLE_ID, code: RoleCode.EDITOR }, ] }; else return null; }); export const mockRoleRepoFindByCode = jest.fn( - async (code: string): Promise => { + async (code: string): Promise => { switch (code) { - case RoleCode.WRITER: return { + case RoleCode.WRITER: return { _id: WRITER_ROLE_ID, code: RoleCode.WRITER, status: true }; - case RoleCode.EDITOR: return { + case RoleCode.EDITOR: return { _id: EDITOR_ROLE_ID, code: RoleCode.EDITOR, status: true }; - case RoleCode.LEARNER: return { + case RoleCode.LEARNER: return { _id: LEARNER_ROLE_ID, code: RoleCode.LEARNER, status: true diff --git a/tests/routes/v1/blog/blogDetail/mock.ts b/tests/routes/v1/blog/blogDetail/mock.ts index 27dbc55..fcb3931 100644 --- a/tests/routes/v1/blog/blogDetail/mock.ts +++ b/tests/routes/v1/blog/blogDetail/mock.ts @@ -1,4 +1,4 @@ -import { IBlog } from '../../../../../src/database/model/Blog'; +import Blog from '../../../../../src/database/model/Blog'; import { Types } from 'mongoose'; jest.unmock('../../../../../src/database/repository/BlogRepo'); @@ -6,16 +6,16 @@ jest.unmock('../../../../../src/database/repository/BlogRepo'); export const BLOG_ID = new Types.ObjectId(); export const BLOG_URL = 'abc'; -export const mockBlogFindByUrl = jest.fn(async (blogUrl: string): Promise => { - if (blogUrl === BLOG_URL) return { +export const mockBlogFindByUrl = jest.fn(async (blogUrl: string): Promise => { + if (blogUrl === BLOG_URL) return { _id: BLOG_ID, blogUrl: blogUrl }; return null; }); -export const mockFindInfoWithTextById = jest.fn(async (id: Types.ObjectId): Promise => { - if (BLOG_ID.equals(id)) return { +export const mockFindInfoWithTextById = jest.fn(async (id: Types.ObjectId): Promise => { + if (BLOG_ID.equals(id)) return { _id: BLOG_ID, blogUrl: BLOG_URL }; diff --git a/tests/routes/v1/blog/writer/mock.ts b/tests/routes/v1/blog/writer/mock.ts index 831f695..18201b9 100644 --- a/tests/routes/v1/blog/writer/mock.ts +++ b/tests/routes/v1/blog/writer/mock.ts @@ -1,4 +1,4 @@ -import { IBlog } from '../../../../../src/database/model/Blog'; +import Blog from '../../../../../src/database/model/Blog'; import { Types } from 'mongoose'; import { USER_ID_WRITER } from '../../../../auth/authorization/mock'; @@ -8,30 +8,30 @@ export const BLOG_ID = new Types.ObjectId(); export const BLOG_ID_2 = new Types.ObjectId(); export const BLOG_URL = 'abc'; -export const mockBlogFindUrlIfExists = jest.fn(async (blogUrl: string): Promise => { - if (blogUrl === BLOG_URL) return { +export const mockBlogFindUrlIfExists = jest.fn(async (blogUrl: string): Promise => { + if (blogUrl === BLOG_URL) return { _id: BLOG_ID, blogUrl: blogUrl }; return null; }); -export const mockBlogCreate = jest.fn(async (blog: IBlog): Promise => { +export const mockBlogCreate = jest.fn(async (blog: Blog): Promise => { blog._id = BLOG_ID; return blog; }); -export const mockBlogUpdate = jest.fn(async (blog: IBlog): Promise => blog); +export const mockBlogUpdate = jest.fn(async (blog: Blog): Promise => blog); -export const mockFindBlogAllDataById = jest.fn(async (id: Types.ObjectId): Promise => { - if (BLOG_ID.equals(id)) return { +export const mockFindBlogAllDataById = jest.fn(async (id: Types.ObjectId): Promise => { + if (BLOG_ID.equals(id)) return { _id: BLOG_ID, author: { _id: USER_ID_WRITER }, isDraft: true, isSubmitted: false, isPublished: false }; - if (BLOG_ID_2.equals(id)) return { + if (BLOG_ID_2.equals(id)) return { _id: BLOG_ID, author: { _id: new Types.ObjectId() }, isDraft: true, diff --git a/tests/routes/v1/login/integration.test.ts b/tests/routes/v1/login/integration.test.ts index b017fc1..fa11907 100644 --- a/tests/routes/v1/login/integration.test.ts +++ b/tests/routes/v1/login/integration.test.ts @@ -4,12 +4,12 @@ import supertest from 'supertest'; import app from '../../../../src/app'; import UserRepo from '../../../../src/database/repository/UserRepo'; import KeystoreRepo from '../../../../src/database/repository/KeystoreRepo'; -import User, { IUser } from '../../../../src/database/model/User'; +import User, { UserModel } from '../../../../src/database/model/User'; import bcrypt from 'bcrypt'; import * as authUtils from '../../../../src/auth/authUtils'; -import { IRole, RoleCode } from '../../../../src/database/model/Role'; +import Role, { RoleCode } from '../../../../src/database/model/Role'; import { Types } from 'mongoose'; -import ApiKey, { IApiKey } from '../../../../src/database/model/ApiKey'; +import ApiKey, { ApiKeyModel } from '../../../../src/database/model/ApiKey'; export const createTokensSpy = jest.spyOn(authUtils, 'createTokens'); export const bcryptCompareSpy = jest.spyOn(bcrypt, 'compare'); @@ -22,12 +22,12 @@ describe('Login basic route', () => { const request = supertest(app); const password = '123456'; - let user: IUser; - let apikey: IApiKey; + let user: User; + let apikey: ApiKey; beforeAll(async () => { - await User.remove({}); // delete all data from user table - user = await User.create({ + await UserModel.remove({}); // delete all data from user table + user = await UserModel.create({ name: 'abc', email: 'abc@xyz.com', password: bcrypt.hashSync(password, 10), @@ -35,13 +35,13 @@ describe('Login basic route', () => { updatedAt: new Date(), createdAt: new Date(), profilePicUrl: 'https:/abc.com/xyz', - roles: [{ _id: new Types.ObjectId(), code: RoleCode.LEARNER }] + roles: [{ _id: new Types.ObjectId(), code: RoleCode.LEARNER }] }); - apikey = await ApiKey.findOne({ status: true }); + apikey = await ApiKeyModel.findOne({ status: true }); }); afterAll(async () => { - await User.remove({}); // delete all data from user table + await UserModel.remove({}); // delete all data from user table }); beforeEach(() => { @@ -178,6 +178,6 @@ describe('Login basic route', () => { }); }); -export const addHeaders = (request: any, apikey: IApiKey) => request +export const addHeaders = (request: any, apikey: ApiKey) => request .set('Content-Type', 'application/json') .set('x-api-key', apikey.key); \ No newline at end of file diff --git a/tests/routes/v1/login/mock.ts b/tests/routes/v1/login/mock.ts index 219ec61..8cc3337 100644 --- a/tests/routes/v1/login/mock.ts +++ b/tests/routes/v1/login/mock.ts @@ -1,6 +1,6 @@ import { USER_ID } from '../../../auth/authentication/mock'; -import { IKeystore } from '../../../../src/database/model/Keystore'; -import { IUser } from '../../../../src/database/model/User'; +import Keystore from '../../../../src/database/model/Keystore'; +import User from '../../../../src/database/model/User'; import { Types } from 'mongoose'; import bcrypt from 'bcrypt'; import * as authUtils from '../../../../src/auth/authUtils'; @@ -15,8 +15,8 @@ export const bcryptCompareSpy = jest.spyOn(bcrypt, 'compare'); export const mockKeystoreCreate = jest.fn( - async (client: IUser, primaryKey: string, secondaryKey: string): Promise => { - return { + async (client: User, primaryKey: string, secondaryKey: string): Promise => { + return { _id: new Types.ObjectId(), client: client, primaryKey: primaryKey, @@ -25,8 +25,8 @@ export const mockKeystoreCreate = }); export const mockUserFindByEmail = - jest.fn(async (email: string): Promise => { - if (email === USER_EMAIL) return { + jest.fn(async (email: string): Promise => { + if (email === USER_EMAIL) return { _id: USER_ID, email: USER_EMAIL, password: USER_PASSWORD_HASH, diff --git a/tests/routes/v1/signup/mock.ts b/tests/routes/v1/signup/mock.ts index 8e453c9..665cd8f 100644 --- a/tests/routes/v1/signup/mock.ts +++ b/tests/routes/v1/signup/mock.ts @@ -1,6 +1,6 @@ import { mockUserFindByEmail } from '../login/mock'; -import { IUser } from '../../../../src/database/model/User'; -import { IKeystore } from '../../../../src/database/model/Keystore'; +import User from '../../../../src/database/model/User'; +import Keystore from '../../../../src/database/model/Keystore'; import { Types } from 'mongoose'; import bcrypt from 'bcrypt'; @@ -9,13 +9,13 @@ export const USER_PROFILE_PIC = 'https://abc.com/xyz'; export const bcryptHashSpy = jest.spyOn(bcrypt, 'hash'); -export const mockUserCreate = jest.fn(async (user: IUser, accessTokenKey: string, refreshTokenKey: string, roleCode: string) - : Promise<{ user: IUser, keystore: IKeystore }> => { +export const mockUserCreate = jest.fn(async (user: User, accessTokenKey: string, refreshTokenKey: string, roleCode: string) + : Promise<{ user: User, keystore: Keystore }> => { user._id = new Types.ObjectId(); user.roles = []; return { user: user, - keystore: { + keystore: { _id: new Types.ObjectId(), client: user, primaryKey: 'abc',