Skip to content

Commit

Permalink
book changes for api server (#156)
Browse files Browse the repository at this point in the history
  • Loading branch information
tima101 committed May 25, 2021
1 parent 3be5f67 commit 880cc17
Show file tree
Hide file tree
Showing 133 changed files with 493 additions and 450 deletions.
4 changes: 2 additions & 2 deletions book/10-begin/api/server/api/team-leader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,11 @@ router.post('/stripe/fetch-checkout-session', async (req, res, next) => {
try {
const { mode, teamId } = req.body;

const user = await User.findById(req.user.id).select(['stripeCustomer', 'email']).lean();
const user = await User.findById(req.user.id).select(['stripeCustomer', 'email']).setOptions({ lean: true });

const team = await Team.findById(teamId)
.select(['stripeSubscription', 'slug', 'teamLeaderId'])
.lean();
.setOptions({ lean: true });

if (!user || !team || team.teamLeaderId !== req.user.id) {
throw new Error('Permission denied');
Expand Down
2 changes: 1 addition & 1 deletion book/10-begin/api/server/aws-s3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ async function signRequestForUpload({ fileName, fileType, prefix, bucket }) {

const s3 = new aws.S3({
apiVersion: 'latest',
region: 'us-east-1',
region: process.env.AWS_REGION,
accessKeyId: process.env.AWS_ACCESSKEYID,
secretAccessKey: process.env.AWS_SECRETACCESSKEY,
});
Expand Down
2 changes: 1 addition & 1 deletion book/10-begin/api/server/aws-ses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import * as aws from 'aws-sdk';
export default function sendEmail(options) {
const ses = new aws.SES({
apiVersion: 'latest',
region: 'us-east-1',
region: process.env.AWS_REGION,
accessKeyId: process.env.AWS_ACCESSKEYID,
secretAccessKey: process.env.AWS_SECRETACCESSKEY,
});
Expand Down
14 changes: 9 additions & 5 deletions book/10-begin/api/server/models/Discussion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ const mongoSchema = new mongoose.Schema({
type: String,
required: true,
},
memberIds: [String],
memberIds: [
{
type: String,
},
],
createdAt: {
type: Date,
required: true,
Expand Down Expand Up @@ -104,7 +108,7 @@ class DiscussionClass extends mongoose.Model {

const filter: any = { teamId, memberIds: userId };

const discussions: any[] = await this.find(filter).lean();
const discussions: any[] = await this.find(filter).setOptions({ lean: true });

return { discussions };
}
Expand Down Expand Up @@ -134,7 +138,7 @@ class DiscussionClass extends mongoose.Model {
throw new Error('Bad data');
}

const discussion = await this.findById(id).select('teamId createdUserId').lean();
const discussion = await this.findById(id).select('teamId createdUserId').setOptions({ lean: true });

const team = await this.checkPermissionAndGetTeam({
userId,
Expand Down Expand Up @@ -164,7 +168,7 @@ class DiscussionClass extends mongoose.Model {
throw new Error('Bad data');
}

const discussion = await this.findById(id).select('teamId').lean();
const discussion = await this.findById(id).select('teamId').setOptions({ lean: true });

await this.checkPermissionAndGetTeam({ userId, teamId: discussion.teamId });

Expand All @@ -180,7 +184,7 @@ class DiscussionClass extends mongoose.Model {
throw new Error('Bad data');
}

const team = await Team.findById(teamId).select('memberIds teamLeaderId').lean();
const team = await Team.findById(teamId).select('memberIds teamLeaderId').setOptions({ lean: true });

if (!team || team.memberIds.indexOf(userId) === -1) {
throw new Error('Team not found');
Expand Down
4 changes: 2 additions & 2 deletions book/10-begin/api/server/models/EmailTemplate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export async function insertTemplates() {
];

for (const t of templates) {
const et = await EmailTemplate.findOne({ name: t.name }).lean();
const et = await EmailTemplate.findOne({ name: t.name }).setOptions({ lean: true });
const message = t.message.replace(/\n/g, '').replace(/[ ]+/g, ' ').trim();

if (!et) {
Expand All @@ -88,7 +88,7 @@ export async function insertTemplates() {
export default async function getEmailTemplate(name: string, params: any) {
await insertTemplates();

const et = await EmailTemplate.findOne({ name }).lean();
const et = await EmailTemplate.findOne({ name }).setOptions({ lean: true });

if (!et) {
throw new Error('Email Template is not found in database.');
Expand Down
24 changes: 12 additions & 12 deletions book/10-begin/api/server/models/Invitation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,12 @@ class InvitationClass extends mongoose.Model {
throw new Error('Bad data');
}

const team = await Team.findById(teamId).lean();
const team = await Team.findById(teamId).setOptions({ lean: true });
if (!team || team.teamLeaderId !== userId) {
throw new Error('Team does not exist or you have no permission');
}

const registeredUser = await User.findOne({ email }).select('defaultTeamSlug').lean();
const registeredUser = await User.findOne({ email }).select('defaultTeamSlug').setOptions({ lean: true });

if (registeredUser) {
if (team.memberIds.includes(registeredUser._id.toString())) {
Expand All @@ -90,7 +90,7 @@ class InvitationClass extends mongoose.Model {
}

let token;
const invitation = await this.findOne({ teamId, email }).select('token').lean();
const invitation = await this.findOne({ teamId, email }).select('token').setOptions({ lean: true });

if (invitation) {
token = invitation.token;
Expand Down Expand Up @@ -125,33 +125,33 @@ class InvitationClass extends mongoose.Model {
console.log('Email sending error:', err);
});

return await this.findOne({ teamId, email }).lean();
return await this.findOne({ teamId, email }).setOptions({ lean: true });
}

public static async getTeamInvitations({ userId, teamId }) {
const team = await Team.findOne({ _id: teamId }).select('teamLeaderId').lean();
const team = await Team.findOne({ _id: teamId }).select('teamLeaderId').setOptions({ lean: true });

if (userId !== team.teamLeaderId) {
throw new Error('You have no permission.');
}

return this.find({ teamId }).select('email').lean();
return this.find({ teamId }).select('email').setOptions({ lean: true });
}

public static async getTeamByToken({ token }) {
if (!token) {
throw new Error('Bad data');
}

const invitation = await this.findOne({ token }).lean();
const invitation = await this.findOne({ token }).setOptions({ lean: true });

if (!invitation) {
throw new Error('Invitation not found');
}

const team = await Team.findById(invitation.teamId)
.select('name slug avatarUrl memberIds')
.lean();
.setOptions({ lean: true });

if (!team) {
throw new Error('Team does not exist');
Expand All @@ -165,15 +165,15 @@ class InvitationClass extends mongoose.Model {
throw new Error('Bad data');
}

const invitation = await this.findOne({ token }).lean();
const invitation = await this.findOne({ token }).setOptions({ lean: true });

if (!invitation) {
throw new Error('Invitation not found');
}

const team = await Team.findById(invitation.teamId)
.select('name slug avatarUrl memberIds')
.lean();
.setOptions({ lean: true });

if (!team) {
throw new Error('Team does not exist');
Expand All @@ -189,7 +189,7 @@ class InvitationClass extends mongoose.Model {
throw new Error('Bad data');
}

const invitation = await this.findOne({ token }).lean();
const invitation = await this.findOne({ token }).setOptions({ lean: true });

if (!invitation || invitation.email !== user.email) {
throw new Error('Invitation not found');
Expand All @@ -199,7 +199,7 @@ class InvitationClass extends mongoose.Model {

const team = await Team.findById(invitation.teamId)
.select('memberIds slug teamLeaderId')
.lean();
.setOptions({ lean: true });

if (!team) {
throw new Error('Team does not exist');
Expand Down
10 changes: 5 additions & 5 deletions book/10-begin/api/server/models/Post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ class PostClass extends mongoose.Model {

const filter: any = { discussionId };

const posts: any[] = await this.find(filter).sort({ createdAt: 1 }).lean();
const posts: any[] = await this.find(filter).sort({ createdAt: 1 }).setOptions({ lean: true });

return posts;
}
Expand Down Expand Up @@ -156,7 +156,7 @@ class PostClass extends mongoose.Model {
throw new Error('Bad data');
}

const post = await this.findById(id).select('createdUserId discussionId').lean();
const post = await this.findById(id).select('createdUserId discussionId').setOptions({ lean: true });

await this.checkPermissionAndGetTeamAndDiscussion({
userId,
Expand All @@ -180,7 +180,7 @@ class PostClass extends mongoose.Model {
throw new Error('Bad data');
}

const post = await this.findById(id).select('createdUserId discussionId content').lean();
const post = await this.findById(id).select('createdUserId discussionId content').setOptions({ lean: true });

await this.checkPermissionAndGetTeamAndDiscussion({
userId,
Expand All @@ -206,7 +206,7 @@ class PostClass extends mongoose.Model {

const discussion = await Discussion.findById(discussionId)
.select('teamId memberIds slug')
.lean();
.setOptions({ lean: true });

if (!discussion) {
throw new Error('Discussion not found');
Expand All @@ -216,7 +216,7 @@ class PostClass extends mongoose.Model {
throw new Error('Permission denied');
}

const team = await Team.findById(discussion.teamId).select('memberIds slug').lean();
const team = await Team.findById(discussion.teamId).select('memberIds slug').setOptions({ lean: true });

if (!team || team.memberIds.indexOf(userId) === -1) {
throw new Error('Team not found');
Expand Down
20 changes: 11 additions & 9 deletions book/10-begin/api/server/models/Team.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@ const mongoSchema = new mongoose.Schema({
type: String,
required: true,
},
memberIds: {
type: [String],
required: true,
},
memberIds: [
{
type: String,
required: true,
},
],
defaultTeam: {
type: Boolean,
default: false,
Expand Down Expand Up @@ -183,12 +185,12 @@ class TeamClass extends mongoose.Model {

await this.updateOne({ _id: teamId }, { $set: modifier }, { runValidators: true });

return this.findById(teamId, 'name avatarUrl slug defaultTeam').lean();
return this.findById(teamId, 'name avatarUrl slug defaultTeam').setOptions({ lean: true });
}

public static getAllTeamsForUser(userId: string) {
console.log(`userId:${userId}`);
return this.find({ memberIds: userId }).lean();
return this.find({ memberIds: userId }).setOptions({ lean: true });
}

public static async removeMember({ teamId, teamLeaderId, userId }) {
Expand Down Expand Up @@ -259,13 +261,13 @@ class TeamClass extends mongoose.Model {
{ new: true, runValidators: true },
)
.select('isSubscriptionActive stripeSubscription')
.lean();
.setOptions({ lean: true });
}

public static async cancelSubscriptionAfterFailedPayment({ subscriptionId }) {
const team: any = await this.find({ 'stripeSubscription.id': subscriptionId })
.select('teamLeaderId isSubscriptionActive stripeSubscription isPaymentFailed')
.lean();
.setOptions({ lean: true });
if (!team.isSubscriptionActive) {
throw new Error('Team is already unsubscribed.');
}
Expand All @@ -285,7 +287,7 @@ class TeamClass extends mongoose.Model {
{ new: true, runValidators: true },
)
.select('isSubscriptionActive stripeSubscription isPaymentFailed')
.lean();
.setOptions({ lean: true });
}
}

Expand Down
14 changes: 7 additions & 7 deletions book/10-begin/api/server/models/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ class UserClass extends mongoose.Model {
public static async getUserBySlug({ slug }) {
console.log('Static method: getUserBySlug');

return this.findOne({ slug }, 'email displayName avatarUrl').lean();
return this.findOne({ slug }, 'email displayName avatarUrl').setOptions({ lean: true });
}

public static async updateProfile({ userId, name, avatarUrl }) {
Expand All @@ -240,7 +240,7 @@ class UserClass extends mongoose.Model {

return this.findByIdAndUpdate(userId, { $set: modifier }, { new: true, runValidators: true })
.select('displayName avatarUrl slug')
.lean();
.setOptions({ lean: true });
}

public static publicFields(): string[] {
Expand Down Expand Up @@ -269,7 +269,7 @@ class UserClass extends mongoose.Model {
}) {
const user = await this.findOne({ email })
.select([...this.publicFields(), 'googleId'].join(' '))
.lean();
.setOptions({ lean: true });

if (user) {
if (_.isEmpty(googleToken) && user.googleId) {
Expand Down Expand Up @@ -331,7 +331,7 @@ class UserClass extends mongoose.Model {
}

public static async signInOrSignUpByPasswordless({ uid, email }) {
const user = await this.findOne({ email }).select(this.publicFields().join(' ')).lean();
const user = await this.findOne({ email }).select(this.publicFields().join(' ')).setOptions({ lean: true });

if (user) {
throw Error('User already exists');
Expand Down Expand Up @@ -382,7 +382,7 @@ class UserClass extends mongoose.Model {

return this.find({ _id: { $in: team.memberIds } })
.select(this.publicFields().join(' '))
.lean();
.setOptions({ lean: true });
}

public static async saveStripeCustomerAndCard({
Expand Down Expand Up @@ -456,7 +456,7 @@ class UserClass extends mongoose.Model {

return this.findByIdAndUpdate(userId, { $set: modifier }, { new: true, runValidators: true })
.select('stripeListOfInvoices')
.lean();
.setOptions({ lean: true });
}

private static async checkPermissionAndGetTeam({ userId, teamId }) {
Expand All @@ -466,7 +466,7 @@ class UserClass extends mongoose.Model {
throw new Error('Bad data');
}

const team = await Team.findById(teamId).select('memberIds').lean();
const team = await Team.findById(teamId).select('memberIds').setOptions({ lean: true });

if (!team || team.memberIds.indexOf(userId) === -1) {
throw new Error('Team not found');
Expand Down
2 changes: 1 addition & 1 deletion book/10-begin/api/server/passwordless-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function setupPasswordless({ server }) {
'/auth/email-login-link',
passwordless.requestToken(async (email, __, callback) => {
try {
const user = await User.findOne({ email }).select('_id').lean();
const user = await User.findOne({ email }).select('_id').setOptions({ lean: true });

if (user) {
callback(null, user._id);
Expand Down
4 changes: 2 additions & 2 deletions book/10-begin/api/server/passwordless-token-mongostore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ MongoStore.prototype.authenticate = async function (token, uid, callback) {
}

try {
const tokenDoc = await PasswordlessToken.findOne({ uid, ttl: { $gt: new Date() } }).lean();
const tokenDoc = await PasswordlessToken.findOne({ uid, ttl: { $gt: new Date() } }).setOptions({ lean: true });

if (tokenDoc) {
const isMatch = await bcrypt.compare(token, tokenDoc.hashedToken);
Expand Down Expand Up @@ -130,7 +130,7 @@ MongoStore.prototype.storeOrUpdateByEmail = async function addEmail(email: strin
throw new Error('TokenStore:addEmail called with invalid parameters');
}

const obj = await PasswordlessToken.findOne({ email }).select('uid').lean();
const obj = await PasswordlessToken.findOne({ email }).select('uid').setOptions({ lean: true });

if (obj) {
return obj.uid;
Expand Down

0 comments on commit 880cc17

Please sign in to comment.