Skip to content

Commit 47e4a57

Browse files
init
0 parents  commit 47e4a57

File tree

7 files changed

+305
-0
lines changed

7 files changed

+305
-0
lines changed

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
dist
2+
node_modules
3+
yarn.lock
4+
.idea

README.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# TempMail.lol JS API
2+
3+
This is an API for the temporary email service [TempMail.lol](https://tempmail.lol).
4+
5+
## Installation
6+
```bash
7+
npm i tempmail.lol
8+
# or, if you use yarn
9+
yarn add tempmail.lol
10+
```
11+
12+
This has built-in types.
13+
14+
## Usage
15+
16+
### Create inbox
17+
18+
To create an inbox, you can use one of the following two functions:
19+
```js
20+
//with callback
21+
createInbox((inbox) => {
22+
console.log(`Created new inbox: ${inbox.address}, token: ${inbox.token}`);
23+
});
24+
25+
//async
26+
createInboxAsync().then((inbox) => {
27+
console.log(`Created new inbox: ${inbox.address}, token: ${inbox.token}`);
28+
});
29+
30+
//await
31+
const inbox = await createInboxAsync();
32+
```
33+
34+
### Retrieve emails
35+
36+
To get the emails (you can also pass in the Inbox object instead of a token string):
37+
```js
38+
//with callback
39+
checkInbox("token", (emails) => {
40+
emails.forEach((e) => {
41+
console.log(JSON.stringify(e, null, 4));
42+
});
43+
});
44+
45+
//async
46+
checkInboxAsync("token").then((emails) => {
47+
emails.forEach((e) => {
48+
console.log(JSON.stringify(e, null, 4));
49+
});
50+
});
51+
52+
//await
53+
const emails = await checkInboxAsync("token");
54+
```

package.json

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
{
2+
"name": "tempmail.lol",
3+
"version": "1.0.4",
4+
"description": "API to generate temporary email addresses.",
5+
"main": "dist/index.js",
6+
"types": "dist/index.d.ts",
7+
"scripts": {
8+
"test": "echo \"Error: no test specified\" && exit 1"
9+
},
10+
"keywords": [
11+
"tempmail",
12+
"lol",
13+
"email",
14+
"temporary-email",
15+
"generator",
16+
"api",
17+
"nodejs"
18+
],
19+
"author": "Alexander Epolite <alexander@epolite.net>",
20+
"license": "ISC",
21+
"devDependencies": {
22+
"@types/node": "^17.0.32",
23+
"@types/node-fetch": "^2.6.1"
24+
},
25+
"dependencies": {
26+
"tslib": "^2.4.0",
27+
"node-fetch": "^2.6.7"
28+
},
29+
"repository": {
30+
"type": "git",
31+
"url": "https://github.com/alexanderepolite/tempmail.lol.git"
32+
}
33+
}

src/Email.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
2+
export default class Email {
3+
4+
public constructor(
5+
public readonly from: string,
6+
public readonly to: string,
7+
public readonly subject: string,
8+
public readonly body: string,
9+
public readonly html: string | null,
10+
public readonly date: number,
11+
) {}
12+
13+
}

src/Inbox.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
2+
export default class Inbox {
3+
4+
/**
5+
* Inbox entity.
6+
*
7+
* @param address {string} The address of the inbox.
8+
* @param token {string} The token of the inbox.
9+
*/
10+
public constructor(
11+
public address: string,
12+
public token: string,
13+
) {}
14+
15+
}

src/index.ts

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
#!
2+
3+
import Inbox from "./Inbox";
4+
import Email from "./Email";
5+
6+
import fetch from "node-fetch";
7+
8+
const BASE_URL = "https://api.tempmail.lol";
9+
10+
/**
11+
* Create a new Inbox.
12+
* @param cb {function} Callback function.
13+
*/
14+
function createInbox(cb: (inbox: Inbox) => any): void {
15+
fetch(`${BASE_URL}/generate`).then(res => res.json()).then(json => {
16+
const inbox = new Inbox(json.address, json.token);
17+
cb(inbox);
18+
});
19+
}
20+
21+
/**
22+
* Create a new Inbox asynchronously.
23+
* @returns {Promise<Inbox>} Promise with the Inbox.
24+
*/
25+
async function createInboxAsync(): Promise<Inbox> {
26+
const res = await fetch(`${BASE_URL}/generate`);
27+
const json = await res.json();
28+
return new Inbox(json.address, json.token);
29+
}
30+
31+
/**
32+
* Check for new emails on an Inbox.
33+
* @param inbox {Inbox | string} Inbox or token string to check.
34+
* @param cb {function} Callback function.
35+
* @throws {Error} If the token is not valid.
36+
*/
37+
function checkInbox(inbox: Inbox | string, cb: (emails: Email[]) => any): void {
38+
39+
//convert the token to an Inbox
40+
if(typeof inbox === "string") {
41+
inbox = new Inbox("", inbox);
42+
}
43+
44+
fetch(`${BASE_URL}/auth/${inbox.token}`).then(res => res.json()).then(json => {
45+
if(json.token === "invalid") {
46+
throw new Error("Invalid token");
47+
}
48+
if(json.email === null) {
49+
return cb([]);
50+
}
51+
const emails = json.email.map((email: Email) => new Email(email.from, email.to, email.subject, email.body, email.html, email.date));
52+
cb(emails);
53+
});
54+
}
55+
56+
/**
57+
* Check for new emails on an Inbox asynchronously.
58+
*
59+
* @param inbox {Inbox | string} Inbox or token string to check.
60+
* @returns {Promise<Email[]>} Promise with the emails.
61+
* @throws {Error} If the token is invalid.
62+
*/
63+
async function checkInboxAsync(inbox: Inbox | string): Promise<Email[]> {
64+
65+
//convert the token to an Inbox
66+
if(typeof inbox === "string") {
67+
inbox = new Inbox("", inbox);
68+
}
69+
70+
const res = await fetch(`${BASE_URL}/auth/${inbox.token}`);
71+
const json = await res.json();
72+
if(json.token === "invalid") {
73+
throw new Error("Invalid token");
74+
}
75+
if(json.email === null) {
76+
return [];
77+
}
78+
return json.email.map((email: Email) => new Email(email.from, email.to, email.subject, email.body, email.html, email.date));
79+
}
80+
81+
export {
82+
Inbox,
83+
Email,
84+
85+
createInbox, createInboxAsync,
86+
checkInbox, checkInboxAsync,
87+
};

tsconfig.json

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
{
2+
"compilerOptions": {
3+
/* Visit https://aka.ms/tsconfig.json to read more about this file */
4+
5+
/* Projects */
6+
// "incremental": true, /* Enable incremental compilation */
7+
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8+
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
9+
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
10+
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11+
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12+
13+
/* Language and Environment */
14+
"target": "ES2021", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15+
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16+
// "jsx": "preserve", /* Specify what JSX code is generated. */
17+
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18+
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19+
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
20+
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21+
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
22+
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
23+
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24+
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25+
26+
/* Modules */
27+
"module": "commonjs", /* Specify what module code is generated. */
28+
"rootDir": "./src/", /* Specify the root folder within your source files. */
29+
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
30+
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
31+
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
32+
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
33+
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
34+
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
35+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
36+
// "resolveJsonModule": true, /* Enable importing .json files */
37+
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
38+
39+
/* JavaScript Support */
40+
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
41+
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
42+
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
43+
44+
/* Emit */
45+
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
46+
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
47+
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
48+
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
49+
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
50+
"outDir": "./dist/", /* Specify an output folder for all emitted files. */
51+
// "removeComments": true, /* Disable emitting comments. */
52+
// "noEmit": true, /* Disable emitting files from a compilation. */
53+
"importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
54+
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
55+
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
56+
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
57+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
58+
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
59+
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
60+
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
61+
// "newLine": "crlf", /* Set the newline character for emitting files. */
62+
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
63+
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
64+
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
65+
"preserveValueImports": false, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
66+
67+
/* Interop Constraints */
68+
"isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
69+
"allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
70+
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
71+
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
72+
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
73+
74+
/* Type Checking */
75+
"strict": true, /* Enable all strict type-checking options. */
76+
"noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
77+
"strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
78+
"strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
79+
"strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
80+
"strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
81+
"noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
82+
"useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
83+
"alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
84+
"noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
85+
"noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
86+
"exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
87+
"noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
88+
"noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
89+
"noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
90+
"noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
91+
"noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
92+
"allowUnusedLabels": false, /* Disable error reporting for unused labels. */
93+
"allowUnreachableCode": false, /* Disable error reporting for unreachable code. */
94+
95+
/* Completeness */
96+
"skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
97+
"skipLibCheck": true /* Skip type checking all .d.ts files. */
98+
}
99+
}

0 commit comments

Comments
 (0)