Skip to content
This repository was archived by the owner on Sep 25, 2025. It is now read-only.

feat(server): send email - #428

Merged
ojeytonwilliams merged 28 commits into
freeCodeCamp:masterfrom
megajon:feat/sendEmail
Apr 8, 2021
Merged

ojeytonwilliams merged 28 commits into
freeCodeCamp:masterfrom
megajon:feat/sendEmail

Conversation

@megajon

@megajon megajon commented Oct 28, 2020

Copy link
Copy Markdown
Contributor
  • I have read Chapter's contributing guidelines.
  • My pull request has a descriptive title (not a vague title like Update README.md).
  • My pull request targets the master branch of Chapter.

I'm trying to create some tests for the sendEmail resolver but when I run the "npm run test" command I get the error "TypeError: Cannot convert undefined or null to object".

jest_error

@Ryuno-Ki

Ryuno-Ki commented Nov 7, 2020 •

Copy link
Copy Markdown
Contributor

I checked out this PR by running the following:

git remote add megajon https://github.com/megajon/chapter.git
git fetch
git fetch megajon feat/sendEmail:feat/sendEmail
git checkout feat/sendEmail

(The last commit has this branch on the left hand of the colon and the local branch name on the right).

@Ryuno-Ki

Ryuno-Ki commented Nov 7, 2020

Copy link
Copy Markdown
Contributor

Looking closely at the error report shows jest.config.js:13:21 as the faulty one (line 13, column 21 of jest.config.js).
That line means

moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {

So I looked into where compilerOptions.paths comes from. Logging it yields undefined (and thus the above error message).
The reason? No property paths in this object:

chapter/tsconfig.json

Lines 2 to 29 in 2ec3c0b

"compilerOptions": {
"baseUrl": ".",
"allowJs": true,
"allowSyntheticDefaultImports": true,
"jsx": "preserve",
"lib": ["dom", "es2017"],
"module": "esnext",
"moduleResolution": "node",
"noEmit": true,
"noImplicitAny": false,
"noUnusedLocals": true,
"noUnusedParameters": true,
"preserveConstEnums": true,
"removeComments": false,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"target": "ES2020",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strictPropertyInitialization": false,
"strictFunctionTypes": false,
"resolveJsonModule": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"isolatedModules": true,
"types": ["jest", "node"]
},

That line in Jest config was added with 292b1e5 as part of #326. So I'm pinging @phoenisx (creator) and @Zeko369 for more insights into the context of the change there.

@ojeytonwilliams

Copy link
Copy Markdown
Contributor

That's what I found, too. Simply removing moduleNameMapper is enough to get the tests running.

@Ryuno-Ki

Ryuno-Ki commented Nov 7, 2020

Copy link
Copy Markdown
Contributor

It's broken on master, too.

@phoenisx

phoenisx commented Nov 9, 2020

Copy link
Copy Markdown
Contributor

I haven't worked on this project for a long time now, so have lost context.

Anyways, I do remember why I made those changes:

  • Typeform used to throw module not found errors, for the versions installed at that time, as we were using custom aliases for rootPaths.
  • To resolve custom aliases in Jest, moduleNameMapper was required, which was coded to take aliases from tsconfig.json.

Some recent changes:

have removed custom aliases from chapter project setup.

If they are desired changes, then moduleNameMapper can be removed as well 👍

cc: @Zeko369

@ojeytonwilliams

Copy link
Copy Markdown
Contributor

Thanks for taking a look @phoenisx. Am I right in thinking that Jest would fail if the custom aliases were there, but moduleNameMapper was missing or not configured correctly? If so, given that master passes with it removed, it's probably safe to take it out.

@phoenisx

Copy link
Copy Markdown
Contributor

@ojeytonwilliams I have to set up the codebase again (will do it sometime later).

Just by looking in the code, written test cases are very limited and present only for server/* root. Also, these test cases are using relative URLs, instead of absolute, except https://github.com/freeCodeCamp/chapter/blob/master/server/tests/Mailer.test.ts, where:

import Utilities from 'server/util/Utilities'; is absolute, and might not work!!

If the above test is not failing after removing moduleNameMapper, then I am sure you can remove it for now, unless we require aliases mappers later on. 🎉

@megajon

megajon commented Dec 5, 2020

Copy link
Copy Markdown
Contributor Author

I'm having trouble getting input validation to work. I've imported 'class-validator' and added a length restriction to the 'subject' field in server/controllers/Messages/inputs.ts, but when I run the 'sendEmail' resolver from the graphql playground with an empty string in the 'subject' field, the resolver runs successfully when there should be an input validation error.

input_validation

Comment thread jest.config.js Outdated
// moduleDirectories: ['node_modules', 'server'],
// moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {
// prefix: '<rootDir>/',
// }),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From personal experience, I can tell, that it is better to use a block comment + add a line stating the reason, why code is commented (instead of deleted).

@allella

allella commented Dec 8, 2020

Copy link
Copy Markdown
Contributor

@megajon I have zero experience with any of this code stack, but there is an example in the docs that includes MaxLength, so perhaps that's a missing piece of it?

@ojeytonwilliams ojeytonwilliams left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @megajon, I've added a sketch of a solution to the validation issue below.

Comment thread server/controllers/Messages/inputs.ts Outdated
@InputType()
export class SendEmailInputs {
@Field(() => [String])
to: String;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
to: String;
to: [string];

TypeScript was complaining with just String

Comment thread server/controllers/Messages/resolver.ts Resolved
@megajon

megajon commented Feb 8, 2021

Copy link
Copy Markdown
Contributor Author

I've been able to get the input validation and testing to work for the sendEmail resolver. There is still some work to be done regarding sanitization and authentication, but I think its close to being ready to incorporate into other features. I created some custom validation to do some checks that don't appear to be built into the class-validator library, but one of the tests for the resolver is failing because there is no email service to return an email object after the resolver is successfully called. So far I've been using the NodemailerApp on my dev machine as a local email service, but that requires adding configuration in MailerService.ts that I don't want to commit. To make development smoother for everyone I think it might be a good idea to use ethereal as a fake email service for the time being, but I didn't want make those kinds of changes without getting other opinions. Anyone against using ethereal until we figure out what were going to use for a real email service?

@allella

allella commented Feb 11, 2021 •

Copy link
Copy Markdown
Contributor

Thanks for the update @megajon

I believe we're still going to depend on the SMTP protocol and not installing custom Nodemailer plugins, so that gives a good deal of flexibility for development and production environment email configurations.

Ethereal and other "fake" services like Mailtrap should all support SMTP giving each developer a choice of what they want to use for capturing test emails.

I assume there's a sample development environment configuration file, so perhaps that can mention the options for development email, such as Ethereal.

@megajon

megajon commented Mar 5, 2021

Copy link
Copy Markdown
Contributor Author

I was finally able to get the test for a successfully sent email to pass and the test emails are successfully sent to the nodeMailerApp. As I mentioned before there is still some work to be done regarding authentication middleware and input validation, but at this point I think the sendEmail resolver is ready to be merged for development purposes.

@megajon
megajon marked this pull request as ready for review March 5, 2021 23:55
@allella
allella requested a review from Zeko369 March 6, 2021 21:04
@megajon

megajon commented Mar 10, 2021

Copy link
Copy Markdown
Contributor Author

@allella Thanks for pointing out the emails in the tests. I forgot I had hard coded those. I just replaced them with faker emails and everything seems to work fine. The 'From' address is hard coded because the tests are written to run without the server having to be fired up. When the server isn't running the environment variables aren't available so the tests will throw an error if you try to use environment variables in them. I was trying to think of a more dynamic way to do it, but since they're just tests I figured it was ok for now just to hard code the address.

@ojeytonwilliams ojeytonwilliams left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @megajon. I've taken a good look and made some suggestions. There are still a few more things I need to test, but I wanted to see what you thought.

Comment thread .env.example Outdated
DB_NAME=chapter
DB_URL=localhost
IS_DOCKER=true
IS_DOCKER=

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to change the default?

Comment thread server/controllers/Messages/inputs.ts Outdated
to: [];

@Field()
@MaxLength(10)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

10 characters seems a little short for a subject line. Is this just for debugging or does it need to be this short?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I set it to 10 characters so I didn't have to write out a long string in the tests and I wasn't sure what the appropriate limit should be, so I just left it at 10 for now. Any ideas on what the appropriate limit should be?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we're talking about an email address, here's a quote from the standard.

In addition to restrictions on syntax, there is a length limit on email addresses. That limit is a maximum of 64 characters (octets) in the "local part" (before the "@") and a maximum of 255 characters (octets) in the domain part (after the "@") for a total length of 320 characters.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's the email subject and, according to https://stackoverflow.com/questions/1592291/what-is-the-email-subject-length-limit (and the RFC it references) the hard limit (per line) is 998 characters and the recommendation (again, per line) is 78.

I tested gmail and it has the limit of 998, so that might be a good idea. Assuming that nodemailer can cope with that.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By the way, there's a neat function to generate a long string.

var lotsOfAs = 'a'.repeat(999);

@@ -0,0 +1,116 @@
import { expect } from 'chai';
const faker = require('faker');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const faker = require('faker');
import faker from 'faker';

Just for consistency.

},
});

expect(email.errors[0].message).to.equal('Argument Validation Error');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
expect(email.errors[0].message).to.equal('Argument Validation Error');
expect(
email.errors[0].originalError.validationErrors[0].constraints.maxLength,
).to.equal('subject must be shorter than or equal to 10 characters');

I'm a little out of my depth here, but could we try something like this? This way we can confirm that the validation has failed in the way we were expecting.

I know my suggestion makes the test a bit more brittle, but I can't think of a better way yet.

Finally, if we go this route, we should change the other expects too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is exactly what I was trying to do! For some reason neither my vscode nor the console.logs were showing all of the properties available on the email object that gets returned. I spent quite a bit of time trying to figure out how to access the specific error messages being returned, but came up short, which is why I wrote it the other way as a workaround. This is my first time working with graphql, so figuring out how to do proper error handling has been a challenge. I went ahead and made the changes you suggested. Thanks for the assist. Nice to have an extra set of eyes on this.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, this took some trial and error before I even found the properties. Turns out email.errors[0] has a bunch of non-enumerable properties, including the ones we're interested in. console.log does not always show them, so isn't reliable. The easiest way I know to get all the info about an object is to use

const { inspect } = require('util');
console.log(inspect(obj, true, null, true));

if you're in node and have access to util. The options are, respectively, showHidden, depth and color. That should show you everything might be interested in.

export class FindDuplicateEmailsConstraint
implements ValidatorConstraintInterface {
validate(emailList: any) {
let checkedEmails = {};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let checkedEmails = {};
const checkedEmails = {};

Eslint was complaining because this was never reassigned.

@ValidatorConstraint({ async: true })
export class IsListEmptyConstraint implements ValidatorConstraintInterface {
validate(emailList: any) {
return emailList.length === 0 ? false : true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return emailList.length === 0 ? false : true;
return emailList.length !== 0;

We can save a few characters here.

validate(emailList: any) {
const regex = /^[\w.%+\-]+@[\w.\-]+\.[A-Za-z]{2,6}$/;
for (let i = 0; i < emailList.length; i++) {
if (regex.test(emailList[i]) === false) return false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (regex.test(emailList[i]) === false) return false;
if (!regex.test(emailList[i])) return false;

@@ -28,9 +28,10 @@ export default class MailerService implements IMailerService {
this.backupText = backupText || '';

// to be replaced with env vars

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// to be replaced with env vars

Comment thread server/controllers/Messages/inputs.ts Resolved

@ojeytonwilliams ojeytonwilliams left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM 👍

I went ahead and reverted the IS_DOCKER change - I couldn't see a reason to change the default. Also, I removed the changes to package.json and package-lock.json. While we do want to keep them updated, those changes felt out of scope for this PR.

@megajon if you're okay with those changes, I think we can get this in.

@ojeytonwilliams ojeytonwilliams mentioned this pull request Apr 7, 2021
3 tasks done
@megajon

megajon commented Apr 7, 2021

Copy link
Copy Markdown
Contributor Author

@ojeytonwilliams The changes are fine with me. It would be a good idea to create some documentation on how to configure a service to receive the emails sent by the resolver, but I think the code is in good enough shape to be merged.

@ojeytonwilliams

Copy link
Copy Markdown
Contributor

Cool, I'll create a PR for the docs change and ping you for review.

@ojeytonwilliams
ojeytonwilliams merged commit cde15c9 into freeCodeCamp:master Apr 8, 2021
@ojeytonwilliams

Copy link
Copy Markdown
Contributor

This is such a key feature, so thanks for all your hard work and patience. I'm glad we're able to get this in!

@ojeytonwilliams ojeytonwilliams mentioned this pull request Apr 8, 2021
3 tasks done
@allella

allella commented Apr 8, 2021

Copy link
Copy Markdown
Contributor

@megajon will the configuration mostly be in the .env section?

If you want to share rough details I can work it into the documentation.

Thanks

@allella

allella commented Jun 23, 2021

Copy link
Copy Markdown
Contributor

@megajon Could you share an example of the variable names needed in the .env for the mailer service?

Nick (@nhcarrigan) was asking on the chat due to what seemed to be missing values.

I don't recall if that was addressed after the last comment above.

I think all that needs to be done is add sample key=value in the .env.example file and any helpful comments in that file if needed. I can also update the CONTRIBUTING.md if / as needed once we a .env.example to work from.

Thanks

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants