├── .gitignore ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── src └── index.ts └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | node_modules/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 quirrel-dev 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # @quirrel/next 2 | 3 | Quirrel is the Task Queueing Solution for Next.js X Vercel. 4 | 5 | ## Getting Started 6 | 7 | > Check out [Getting Started Guide](https://docs.quirrel.dev) or the [Quirrel Tutorial](https://dev.to/quirrel/building-a-water-drinking-reminder-with-next-js-and-quirrel-1ckj) to get the full picture. 8 | 9 | 1. `npm install @quirrel/next` 10 | 2. Create a new API Route and export a Quirrel Queue: 11 | 12 | ```js 13 | // pages/api/emailQueue.js 14 | import { Queue } from "@quirrel/next" 15 | 16 | export default Queue("emailQueue", async (job) => { 17 | await dispatchEmail(job.recipient, job.subject, ...); 18 | }) 19 | ``` 20 | 21 | 3. Import & use from another file to enqueue jobs: 22 | 23 | ```js 24 | // pages/api/signup.js 25 | ... 26 | import emailQueue from "./emailQueue" 27 | 28 | export default async (req, res) => { 29 | // create user ... 30 | await emailQueue.enqueue({ 31 | recipient: user.email, 32 | subject: "Welcome to Quirrel!", 33 | ... 34 | }) 35 | } 36 | ``` 37 | 38 | ## How does it work? 39 | 40 | When calling `.enqueue`, a request to [api.quirrel.dev](https://api.quirrel.dev) is made. It contains an endpoint to call (in the example above, that'd be `/api/emailQueue`) and a timestamp of when it should be called. 41 | The Quirrel API will then call the corresponding endpoint on time. 42 | 43 | ## In Development 44 | 45 | Quirrel is currently in development. I will post updates [on Twitter](https://twitter.com/skn0tt). 46 | 47 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@quirrel/next", 3 | "version": "0.10.0", 4 | "main": "dist/index.js", 5 | "private": false, 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "build": "tsc", 9 | "prepare": "npm run-script build" 10 | }, 11 | "files": [ 12 | "LICENSE", 13 | "dist/", 14 | "src/" 15 | ], 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/quirrel-dev/quirrel-next.git" 19 | }, 20 | "author": "Simon Knott", 21 | "license": "MIT", 22 | "bugs": { 23 | "url": "https://github.com/quirrel-dev/quirrel-next/issues" 24 | }, 25 | "homepage": "https://github.com/quirrel-dev/quirrel-next#readme", 26 | "peerDependencies": { 27 | "next": ">=9.x" 28 | }, 29 | "devDependencies": { 30 | "@types/node": "^14.6.4", 31 | "next": "^9.5.3", 32 | "typescript": "^4.0.2" 33 | }, 34 | "dependencies": { 35 | "@quirrel/client": "^0.10.0" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { NextApiRequest, NextApiResponse } from "next"; 2 | import { 3 | QuirrelClient, 4 | EnqueueJobOpts, 5 | Job, 6 | DefaultJobOptions, 7 | } from "@quirrel/client"; 8 | 9 | let baseUrl: string | undefined = undefined; 10 | 11 | if (process.env.VERCEL_URL) { 12 | baseUrl = `https://${process.env.VERCEL_URL}/api/`; 13 | } 14 | 15 | if (process.env.QUIRREL_BASE_URL) { 16 | baseUrl = `${process.env.QUIRREL_BASE_URL}/api/`; 17 | } 18 | 19 | if (!baseUrl) { 20 | if (process.env.NODE_ENV === "production") { 21 | throw new Error("Please specify QUIRREL_BASE_URL."); 22 | } else { 23 | baseUrl = "http://localhost:3000/api/"; 24 | } 25 | } 26 | 27 | const encryptionSecret = process.env.QUIRREL_ENCRYPTION_SECRET; 28 | if (process.env.NODE_ENV === "production") { 29 | if (!encryptionSecret) { 30 | throw new Error("Please specify `QUIRREL_ENCRYPTION_SECRET`."); 31 | } 32 | 33 | if (encryptionSecret.length !== 32) { 34 | throw new Error("`QUIRREL_ENCRYPTION_SECRET` must have length 32."); 35 | } 36 | } 37 | 38 | type Enqueue = ( 39 | payload: Payload, 40 | meta?: Omit 41 | ) => Promise; 42 | interface QueueResult { 43 | get(): AsyncIterator; 44 | getById(id: string): Promise; 45 | delete(id: string): Promise; 46 | invoke(id: string): Promise; 47 | enqueue: Enqueue; 48 | } 49 | 50 | export function Queue( 51 | path: string, 52 | handler: (payload: Payload) => Promise, 53 | defaultJobOptions?: DefaultJobOptions 54 | ): QueueResult { 55 | const endpoint = baseUrl + path; 56 | 57 | const quirrel = new QuirrelClient({ 58 | encryptionSecret, 59 | defaultJobOptions, 60 | }); 61 | 62 | async function nextApiHandler(req: NextApiRequest, res: NextApiResponse) { 63 | const { isValid, body } = quirrel.verifyRequestSignature<{ 64 | body: Payload; 65 | }>(req.headers as any, req.body); 66 | if (!isValid) { 67 | return res.status(401).end(); 68 | } 69 | 70 | const { body: payload } = body!; 71 | 72 | console.log(`Received job to ${path}: `, payload); 73 | try { 74 | await handler(payload); 75 | res.status(200).end(); 76 | } catch (error) { 77 | res.status(500).json(error); 78 | throw error; 79 | } 80 | } 81 | 82 | nextApiHandler.enqueue = async ( 83 | payload: Payload, 84 | meta?: Omit 85 | ) => 86 | quirrel.enqueue(endpoint, { 87 | body: { body: payload }, 88 | ...meta, 89 | }); 90 | 91 | nextApiHandler.delete = (jobId: string) => quirrel.delete(endpoint, jobId); 92 | 93 | nextApiHandler.invoke = (jobId: string) => quirrel.invoke(endpoint, jobId); 94 | 95 | nextApiHandler.get = () => quirrel.get(endpoint); 96 | 97 | nextApiHandler.getById = (jobId: string) => quirrel.getById(endpoint, jobId); 98 | 99 | return nextApiHandler; 100 | } 101 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Basic Options */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | "target": "ES5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ 8 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 9 | // "lib": [], /* Specify library files to be included in the compilation. */ 10 | // "allowJs": true, /* Allow javascript files to be compiled. */ 11 | // "checkJs": true, /* Report errors in .js files. */ 12 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 13 | "declaration": true, /* Generates corresponding '.d.ts' file. */ 14 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 15 | "sourceMap": true, /* Generates corresponding '.map' file. */ 16 | // "outFile": "./", /* Concatenate and emit output to single file. */ 17 | "outDir": "./dist", /* Redirect output structure to the directory. */ 18 | "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 19 | // "composite": true, /* Enable project compilation */ 20 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 21 | // "removeComments": true, /* Do not emit comments to output. */ 22 | // "noEmit": true, /* Do not emit outputs. */ 23 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 24 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 25 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 26 | 27 | /* Strict Type-Checking Options */ 28 | "strict": true, /* Enable all strict type-checking options. */ 29 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 30 | // "strictNullChecks": true, /* Enable strict null checks. */ 31 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 32 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 33 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 34 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 35 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 36 | 37 | /* Additional Checks */ 38 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 39 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 40 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 41 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 42 | 43 | /* Module Resolution Options */ 44 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 45 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 46 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 47 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 48 | // "typeRoots": [], /* List of folders to include type definitions from. */ 49 | // "types": [], /* Type declaration files to be included in compilation. */ 50 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 51 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 52 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 53 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 54 | 55 | /* Source Map Options */ 56 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 57 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 58 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 59 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 60 | 61 | /* Experimental Options */ 62 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 63 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 64 | 65 | /* Advanced Options */ 66 | "skipLibCheck": true, /* Skip type checking of declaration files. */ 67 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 68 | } 69 | } 70 | --------------------------------------------------------------------------------