first commit

This commit is contained in:
m5r 2021-06-01 23:13:51 +02:00
commit 4c9b1ea9b1
48 changed files with 24046 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
node_modules/
.idea/

8
api/.dockerignore Normal file
View File

@ -0,0 +1,8 @@
node_modules
Dockerfile
.dockerignore
.github
dist
.example.env
docker-compose.yml
README.md

5
api/.example.env Normal file
View File

@ -0,0 +1,5 @@
PORT=3000
NODE_ENV=development
DATABASE_URL=postgres://user:pass@localhost:5432/apidb
TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
TWILIO_AUTH_TOKEN=your_auth_token

25
api/.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: CI
on:
pull_request:
branches:
- master
push:
branches:
- master
jobs:
build:
name: Build the project
runs-on: ubuntu-16.04
steps:
- uses: actions/checkout@master
- uses: actions/setup-node@v1
with:
node-version: '12.x'
- name: Install dependencies
run: npm ci
- name: Building the project
run: npm run build
- name: Unit tests
run: npm run test

21
api/.gitignore vendored Normal file
View File

@ -0,0 +1,21 @@
# API keys and secrets
.env
# Dependency directory
node_modules
bower_components
# Editors
.idea
*.iml
# OS metadata
.DS_Store
Thumbs.db
# Ignore built ts files
dist/**/*
# Logging files
*.log
*.pyc

13
api/Dockerfile Normal file
View File

@ -0,0 +1,13 @@
FROM node:14-alpine
RUN mkdir -p /home/node/app/node_modules && chown -R node:node /home/node/app
WORKDIR /home/node/app
COPY package*.json ./
USER node
RUN npm install
COPY --chown=node:node . .
RUN npm run build
EXPOSE 3000
CMD [ "npm", "run", "start" ]

560
api/README.md Normal file
View File

@ -0,0 +1,560 @@
# Node - Koa - Typescript Project
[![NPM version](https://img.shields.io/npm/v/node-typescript-koa-rest.svg)](https://www.npmjs.com/package/node-typescript-koa-rest)
[![Dependency Status](https://david-dm.org/javieraviles/node-typescript-koa-rest.svg)](https://david-dm.org/javieraviles/node-typescript-koa-rest)
The main purpose of this repository is to build a good project setup and workflow for writing a Node api rest in TypeScript using KOA and an SQL DB.
Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. Through leveraging generators Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any middleware within core, and provides an elegant suite of methods that make writing servers fast and enjoyable.
Through Github Actions CI, this boilerplate is deployed [here](https://node-typescript-koa-rest.herokuapp.com/)! You can try to make requests to the different defined endpoints and see how it works. The following Authorization header will have to be set (already signed with the boilerplate's secret) to pass the JWT middleware:
HEADER (DEMO)
```
Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJuYW1lIjoiSmF2aWVyIEF2aWxlcyIsImVtYWlsIjoiYXZpbGVzbG9wZXouamF2aWVyQGdtYWlsLmNvbSJ9.7oxEVGy4VEtaDQyLiuoDvzdO0AyrNrJ_s9NU3vko5-k
```
AVAILABLE ENDPOINTS DEMO [SWAGGER DOCS DEMO](https://node-typescript-koa-rest.herokuapp.com/swagger-html)
When running the project locally with `watch-server`, being `.env` file config the very same as `.example.env` file, the swagger docs will be deployed at: `http:localhost:3000/swagger-html`, and the bearer token for authorization should be as follows:
HEADER (LOCALHOST BASED ON DEFAULT SECRET KEY 'your-secret-whatever')
```
Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJuYW1lIjoiSmF2aWVyIEF2aWxlcyIsImVtYWlsIjoiYXZpbGVzbG9wZXouamF2aWVyQGdtYWlsLmNvbSJ9.rgOobROftUYSWphkdNfxoN2cgKiqNXd4Km4oz6Ex4ng
```
| method | resource | description |
|:-------------------|:-----------------|:-----------------------------------------------------------------------------------------------|
| `GET` | `/` | Simple hello world response |
| `GET` | `/users` | returns the collection of users present in the DB |
| `GET` | `/users/:id` | returns the specified id user |
| `POST` | `/users` | creates a user in the DB (object user to be includued in request's body) |
| `PUT` | `/users/:id` | updates an already created user in the DB (object user to be includued in request's body) |
| `DELETE` | `/users/:id` | deletes a user from the DB (JWT token user ID must be the same as the user you want to delete) |
- [Node - Koa - Typescript Project](#node---koa---typescript-project)
- [Pre-reqs](#pre-reqs)
- [Features:](#features)
- [Included middleware:](#included-middleware)
- [Getting Started](#getting-started)
- [Docker (optional)](#docker-optional)
- [Setting up the Database - ORM](#setting-up-the-database---orm)
- [Entities validation](#entities-validation)
- [Environment variables](#environment-variables)
- [Getting TypeScript](#getting-typescript)
- [Project Structure](#project-structure)
- [Configuring TypeScript compilation](#configuring-typescript-compilation)
- [Running the build](#running-the-build)
- [CI: Github Actions](#ci-github-actions)
- [ESLint](#eslint)
- [ESLint rules](#eslint-rules)
- [Running ESLint](#running-eslint)
- [Register cron jobs](#register-cron-jobs)
- [Integrations and load tests](#integrations-and-load-tests)
- [Logging](#logging)
- [Authentication - Security](#authentication---security)
- [CORS](#cors)
- [Helmet](#helmet)
- [Dependencies](#dependencies)
- [dependencies](#dependencies-1)
- [devDependencies](#devdependencies)
- [Changelog](#changelog)
- [1.7.1](#171)
- [1.7.0](#170)
- [1.6.1](#161)
- [1.6.0](#160)
- [1.5.0](#150)
- [1.4.2](#142)
- [1.4.1](#141)
- [1.4.0](#140)
- [1.3.0](#130)
- [1.2.0](#120)
- [1.1.0](#110)
## Pre-reqs
To build and run this app locally you will need:
- Install [Node.js](https://nodejs.org/en/)
## Features:
* Nodemon - server auto-restarts when code changes
* Koa v2
* TypeORM (SQL DB) with basic CRUD included
* Swagger decorator (auto generated swagger docs)
* Class-validator - Decorator based entities validation
* Docker-compose ready to go
* Postman (newman) integration tests
* Locust load tests
* Jest unit tests
* Github actions - CI for building and testing the project
* Cron jobs prepared
## Included middleware:
* @koa/router
* koa-bodyparser
* Winston Logger
* JWT auth koa-jwt
* Helmet (security headers)
* CORS
# Getting Started
- Clone the repository
```
git clone --depth=1 https://github.com/javieraviles/node-typescript-koa-rest.git <project_name>
```
- Install dependencies
```
cd <project_name>
npm install
```
- Run the project directly in TS
```
npm run watch-server
```
- Build and run the project in JS
```
npm run build
npm run start
```
- Run integration or load tests
```
npm run test:integration:local (newman needed)
npm run test:load (locust needed)
```
- Run unit tests
```
npm run test
```
- Run unit tests with coverage
```
npm run test:coverage
```
- Run unit tests on Jest watch mode
```
npm run test:watch
```
## Docker (optional)
A docker-compose file has been added to the project with a postgreSQL (already setting user, pass and dbname as the ORM config is expecting) and an ADMINER image (easy web db client).
It is as easy as go to the project folder and execute the command 'docker-compose up' once you have Docker installed, and both the postgreSQL server and the Adminer client will be running in ports 5432 and 8080 respectively with all the config you need to start playing around.
If you use Docker natively, the host for the server which you will need to include in the ORM configuration file will be localhost, but if you were to run Docker in older Windows versions, you will be using Boot2Docker and probably your virtual machine will use your ip 192.168.99.100 as network adapter (if not, command `docker-machine ip` will tell you). This mean your database host will be the aforementioned ip and in case you want to access the web db client you will also need to go to http://192.168.99.100/8080
## Setting up the Database - ORM
This API is prepared to work with an SQL database, using [TypeORM](https://github.com/typeorm/typeorm). In this case we are using postgreSQL, and that is why in the package.json 'pg' has been included. If you where to use a different SQL database remember to install the correspondent driver.
The ORM configuration and connection to the database can be specified in the file 'ormconfig.json'. Here is directly in the connection to the database in 'server.ts' file because a environment variable containing databaseUrl is being used to set the connection data. This is prepared for Heroku, which provides a postgres-string-connection as env variable. In local is being mocked with the docker local postgres as can be seen in ".example.env"
It is importante to notice that, when serving the project directly with *.ts files using ts-node,the configuration for the ORM should specify the *.ts files path, but once the project is built (transpiled) and run as plain js, it will be needed to change it accordingly to find the built js files:
```
"entities": [
"dist/entity/**/*.js"
],
"migrations": [
"dist/migration/**/*.js"
],
"subscribers": [
"dist/subscriber/**/*.js"
]
```
**NOTE: this is now automatically handled by the NODE_ENV variable too.
Notice that if NODE_ENV is set to development, the ORM config won't be using SSL to connect to the DB. Otherwise it will.
And because Heroku uses self-signed certificates, this bit has been added, **please take it out if connecting to a local DB without SSL**.
```
createConnection({
...
extra: {
ssl: {
rejectUnauthorized: false // Heroku uses self signed certificates
}
}
})
```
You can find an implemented **CRUD of the entity user** in the correspondent controller controller/user.ts and its routes in routes.ts file.
## Entities validation
This project uses the library class-validator, a decorator-based entity validation, which is used directly in the entities files as follows:
```
export class User {
@Length(10, 100) // length of string email must be between 10 and 100 characters
@IsEmail() // the string must comply with an standard email format
@IsNotEmpty() // the string can't be empty
email: string;
}
```
Once the decorators have been set in the entity, you can validate from anywhere as follows:
```
const user = new User();
user.email = "avileslopez.javier@gmail"; // should not pass, needs the ending .com to be a valid email
validate(user).then(errors => { // errors is an array of validation errors
if (errors.length > 0) {
console.log("validation failed. errors: ", errors); // code will get here, printing an "IsEmail" error
} else {
console.log("validation succeed");
}
});
```
For further documentation regarding validations see [class-validator docs](https://github.com/typestack/class-validator).
## Environment variables
Create a .env file (or just rename the .example.env) containing all the env variables you want to set, dotenv library will take care of setting them. This project is using three variables at the moment:
* PORT -> port where the server will be started on, Heroku will set this env variable automatically
* NODE_ENV -> environment, development value will set the logger as debug level, also important for CI. In addition will determine if the ORM connects to the DB through SSL or not.
* JWT_SECRET -> secret value, JWT tokens should be signed with this value
* DATABASE_URL -> DB connection data in connection-string format.
## Getting TypeScript
TypeScript itself is simple to add to any project with `npm`.
```
npm install -D typescript
```
If you're using VS Code then you're good to go!
VS Code will detect and use the TypeScript version you have installed in your `node_modules` folder.
For other editors, make sure you have the corresponding [TypeScript plugin](http://www.typescriptlang.org/index.html#download-links).
## Project Structure
The most obvious difference in a TypeScript + Node project is the folder structure.
TypeScript (`.ts`) files live in your `src` folder and after compilation are output as JavaScript (`.js`) in the `dist` folder.
The full folder structure of this app is explained below:
> **Note!** Make sure you have already built the app using `npm run build`
| Name | Description |
| ----------------------------------- | --------------------------------------------------------------------------------------------- |
| **dist** | Contains the distributable (or output) from your TypeScript build. This is the code you ship |
| **node_modules** | Contains all your npm dependencies |
| **src** | Contains your source code that will be compiled to the dist dir |
| **src**/server.ts | Entry point to your KOA app |
| **.github**/**workflows**/ci.yml | Github actions CI configuration |
| **loadtests**/locustfile.py | Locust load tests |
| **integrationtests**/node-koa-typescript.postman_collection.json | Postman integration test collection |
| .copyStaticAssets.ts | Build script that copies images, fonts, and JS libs to the dist folder |
| package.json | File that contains npm dependencies as well as [build scripts](#what-if-a-library-isnt-on-definitelytyped) |
| docker-compose.yml | Docker PostgreSQL and Adminer images in case you want to load the db from Docker |
| tsconfig.json | Config settings for compiling server code written in TypeScript |
| .eslintrc and .eslintignore | Config settings for ESLint code style checking |
| .example.env | Env variables file example to be renamed to .env |
| Dockerfile and dockerignore | The app is dockerized to be deployed from CI in a more standard way, not needed for dev |
## Configuring TypeScript compilation
TypeScript uses the file `tsconfig.json` to adjust project compile options.
Let's dissect this project's `tsconfig.json`, starting with the `compilerOptions` which details how your project is compiled.
```json
"compilerOptions": {
"module": "commonjs",
"target": "es2017",
"lib": ["es6"],
"noImplicitAny": true,
"strictPropertyInitialization": false,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
}
},
```
| `compilerOptions` | Description |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `"module": "commonjs"` | The **output** module type (in your `.js` files). Node uses commonjs, so that is what we use |
| `"target": "es2017"` | The output language level. Node supports ES2017, so we can target that here |
| `"lib": ["es6"]` | Needed for TypeORM. |
| `"noImplicitAny": true` | Enables a stricter setting which throws errors when something has a default `any` value |
| `"moduleResolution": "node"` | TypeScript attempts to mimic Node's module resolution strategy. Read more [here](https://www.typescriptlang.org/docs/handbook/module-resolution.html#node) |
| `"sourceMap": true` | We want source maps to be output along side our JavaScript. |
| `"outDir": "dist"` | Location to output `.js` files after compilation |
| `"baseUrl": "."` | Part of configuring module resolution. |
| `paths: {...}` | Part of configuring module resolution. |
| `"experimentalDecorators": true` | Needed for TypeORM. Allows use of @Decorators |
| `"emitDecoratorMetadata": true` | Needed for TypeORM. Allows use of @Decorators |
The rest of the file define the TypeScript project context.
The project context is basically a set of options that determine which files are compiled when the compiler is invoked with a specific `tsconfig.json`.
In this case, we use the following to define our project context:
```json
"include": [
"src/**/*"
]
```
`include` takes an array of glob patterns of files to include in the compilation.
This project is fairly simple and all of our .ts files are under the `src` folder.
For more complex setups, you can include an `exclude` array of glob patterns that removes specific files from the set defined with `include`.
There is also a `files` option which takes an array of individual file names which overrides both `include` and `exclude`.
## Running the build
All the different build steps are orchestrated via [npm scripts](https://docs.npmjs.com/misc/scripts).
Npm scripts basically allow us to call (and chain) terminal commands via npm.
This is nice because most JavaScript tools have easy to use command line utilities allowing us to not need grunt or gulp to manage our builds.
If you open `package.json`, you will see a `scripts` section with all the different scripts you can call.
To call a script, simply run `npm run <script-name>` from the command line.
You'll notice that npm scripts can call each other which makes it easy to compose complex builds out of simple individual build scripts.
Below is a list of all the scripts this template has available:
| Npm Script | Description |
| ------------------------- | ------------------------------------------------------------------------------------------------- |
| `start` | Does the same as 'npm run serve'. Can be invoked with `npm start` |
| `build` | Full build. Runs ALL build tasks (`build-ts`, `lint`, `copy-static-assets`) |
| `serve` | Runs node on `dist/server/server.js` which is the apps entry point |
| `watch-server` | Nodemon, process restarts if crashes. Continuously watches `.ts` files and re-compiles to `.js` |
| `build-ts` | Compiles all source `.ts` files to `.js` files in the `dist` folder |
| `lint` | Runs ESLint check and fix on project files |
| `copy-static-assets` | Calls script that copies JS libs, fonts, and images to dist directory |
| `test:integration:<env>` | Execute Postman integration tests collection using newman on any env (`local` or `heroku`) |
| `test:load` | Execute Locust load tests using a specific configuration |
# CI: Github Actions
Using Github Actions a pipeline is deploying the application in Heroku and running tests against it, checking the application is healthy deployed. The pipeline can be found at `/.github/workflows/test.yml`. This performs the following:
- Build the project
- Install Node
- Install dependencies
- Build the project (transpile to JS)
- Run unit tests
- Deploy to Heroku
- Install Docker cli
- Build the application container
- Install Heroku cli
- Login into Heroku
- Push Docker image to Heroku
- Trigger release in Heroku
- Run integration tests
- Install Node
- Install Newman
- Run Postman collection using Newman against deployed app in Heroku
- Run load tests
- Install Python
- Install Locust
- Run Locust load tests against deployed app in Heroku
# ESLint
Since TSLint is deprecated now, ESLint feels like the way to go as also supports typescript.
ESLint is a static code analysis tool for identifying problematic patterns found in JavaScript/typescript code.
## ESLint rules
Like most linters, ESLint has a wide set of configurable rules as well as support for custom rule sets.
All rules are configured through `.eslintrc`.
In this project, we are using a fairly basic set of rules with no additional custom rules.
## Running ESLint
Like the rest of our build steps, we use npm scripts to invoke ESLint.
To run ESLint you can call the main build script or just the ESLint task.
```
npm run build // runs full build including ESLint format check
npm run lint // runs ESLint check + fix
```
Notice that ESLint is not a part of the main watch task.
It can be annoying for ESLint to clutter the output window while in the middle of writing a function, so I elected to only run it only during the full build.
If you are interested in seeing ESLint feedback as soon as possible, I strongly recommend the [ESLint extension in VS Code](https://github.com/Microsoft/vscode-eslint.git).
# Register cron jobs
[Cron](https://github.com/node-cron/node-cron) dependency has been added to the project together with types. A `cron.ts` file has been created where a cron job is created using a cron expression configured in `config.ts` file.
```
import { CronJob } from 'cron';
import { config } from './config';
const cron = new CronJob(config.cronJobExpression, () => {
console.log('Executing cron job once every hour');
});
export { cron };
```
From the `server.ts`, the cron job gets started:
```
import { cron } from './cron';
// Register cron job to do any action needed
cron.start();
```
# Integrations and load tests
Integrations tests are a Postman collection with assertions, which gets executed using Newman from the CI (Github Actions). It can be found at `/integrationtests/node-koa-typescript.postman_collection.json`; it can be opened in Postman and get modified very easily. Feel free to install Newman in your local environment and trigger `npm run test:integration:local` command which will use local environment file (instead of heroku dev one) to trigger your postman collection faster than using postman.
Load tests are a locust file with assertions, which gets executed from the CI (Github Actions). It can be found at `/loadtests/locustfile.py`; It is written in python and can be executed locally against any host once python and locust are installed on your dev machine.
**NOTE: at the end of load tests, an endpoint to remove all created test users is called.
# Logging
Winston is designed to be a simple and universal logging library with support for multiple transports.
A "logger" middleware passing a winstonInstance has been created. Current configuration of the logger can be found in the file "logger.ts". It will log 'error' level to an error.log file and 'debug' or 'info' level (depending on NODE_ENV environment variable, debug if == development) to the console.
```
// Logger middleware -> use winston as logger (logger.ts with config)
app.use(logger(winston));
```
# Authentication - Security
The idea is to keep the API as clean as possible, therefore the auth will be done from the client using an auth provider such as Auth0. The client making requests to the API should include the JWT in the Authorization header as "Authorization: Bearer <jwt_token>". HS256 will be used as the secret will be known by both your api and your client and will be used to sign the token, so make sure you keep it hidden.
As can be found in the server.ts file, a JWT middleware has been added, passing the secret from an environment variable. The middleware will validate that every request to the routes below, MUST include a valid JWT signed with the same secret. The middleware will set automatically the payload information in ctx.state.user.
```
// JWT middleware -> below this line, routes are only reached if JWT token is valid, secret as env variable
app.use(jwt({ secret: config.jwtSecret }));
```
Go to the website [https://jwt.io/](https://jwt.io/) to create JWT tokens for testing/debugging purposes. Select algorithm HS256 and include the generated token in the Authorization header to pass through the jwt middleware.
Custom 401 handling -> if you don't want to expose koa-jwt errors to users:
```
app.use(function(ctx, next){
return next().catch((err) => {
if (401 == err.status) {
ctx.status = 401;
ctx.body = 'Protected resource, use Authorization header to get access\n';
} else {
throw err;
}
});
});
```
If you want to authenticate from the API, and you fancy the idea of an auth provider like Auth0, have a look at [jsonwebtoken — JSON Web Token signing and verification](https://github.com/auth0/node-jsonwebtoken)
## CORS
This boilerplate uses @koa/cors, a simple CORS middleware for koa. If you are not sure what this is about, click [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).
```
// Enable CORS with default options
app.use(cors());
```
Have a look at [Official @koa/cors docs](https://github.com/koajs/cors) in case you want to specify 'origin' or 'allowMethods' properties.
## Helmet
This boilerplate uses koa-helmet, a wrapper for helmet to work with koa. It provides important security headers to make your app more secure by default.
Usage is the same as [helmet](https://github.com/helmetjs/helmet). Helmet offers 11 security middleware functions (clickjacking, DNS prefetching, Security Policy...), everything is set by default here.
```
// Enable helmet with default options
app.use(helmet());
```
Have a look at [Official koa-helmet docs](https://github.com/venables/koa-helmet) in case you want to customize which security middlewares are enabled.
# Dependencies
Dependencies are managed through `package.json`.
In that file you'll find two sections:
## dependencies
| Package | Description |
| ------------------------------- | --------------------------------------------------------------------- |
| dotenv | Loads environment variables from .env file. |
| koa | Node web framework. |
| koa-bodyparser | A bodyparser for koa. |
| koa-jwt | Middleware to validate JWT tokens. |
| @koa/router | Router middleware for koa. |
| koa-helmet | Wrapper for helmet, important security headers to make app more secure|
| @koa/cors | Cross-Origin Resource Sharing(CORS) for koa |
| pg | PostgreSQL driver, needed for the ORM. |
| reflect-metadata | Used by typeORM to implement decorators. |
| typeorm | A very cool SQL ORM. |
| winston | Logging library. |
| class-validator | Decorator based entities validation. |
| koa-swagger-decorator | using decorator to automatically generate swagger doc for koa-router. |
| cron | Register cron jobs in node. |
## devDependencies
| Package | Description |
| ------------------------------- | --------------------------------------------------------------------- |
| @types | Dependencies in this folder are `.d.ts` files used to provide types |
| nodemon | Utility that automatically restarts node process when it crashes |
| ts-node | Enables directly running TS files. Used to run `copy-static-assets.ts`|
| eslint | Linter for Javascript/TypeScript files |
| typescript | JavaScript compiler/type checker that boosts JavaScript productivity |
| shelljs | Portable Unix shell commands for Node.js |
To install or update these dependencies you can use `npm install` or `npm update`.
## Changelog
### 1.8.0
- Unit tests included using Jest (Thanks to [@rafapaezbas](https://github.com/rafapaezbas))
- Upgrade all dependencies
- Upgrade to Node 14
### 1.7.1
- Upgrading Locust + fixing load tests
- Improving Logger
### 1.7.0
- Migrating `TSLint` (deprecated already) to `ESLint`
- Node version upgraded from `10.x.x` to `12.0.0` (LTS)
- Now CI installs from `package-lock.json` using `npm ci` (Beyond guaranteeing you that you'll only get what is in your lock-file it's also much faster (2x-10x!) than npm install when you don't start with a node_modules).
- included integraton test using Newman for local env too
- `koa-router` deprecated, using new fork from koa team `@koa/router`
- Dependencies updated, some @types removed as more and more libraries include their own types now!
- Typescript to latest
### 1.6.1
- Fixing CI
- Improving integration tests robustness
### 1.6.0
- CI migrated from Travis to Github actions
- cron dependency -> register cron jobs
- Node app dockerized -> now is directly pushed as a docker image to Heroku from CI, not using any webhook
- Added postman integration tests, executed from Github actions CI using Newman
- Added locust load tests, executed from Github actions CI
- PRs merged: [47](https://github.com/javieraviles/node-typescript-koa-rest/pull/47), [48](https://github.com/javieraviles/node-typescript-koa-rest/pull/48) and [49](https://github.com/javieraviles/node-typescript-koa-rest/pull/49). Thanks to everybody!
### 1.5.0
- koa-swagger-decorator -> generate [swagger docs](https://node-typescript-koa-rest.herokuapp.com/swagger-html) with decorators in the endpoints
- Split routes into protected and unprotected. Hello world + swagger docs are not proteted by jwt
- some dependencies have been updated
### 1.4.2
- Fix -> `npm run watch-server` is now working properly live-reloading changes in the code [Issue 39](https://github.com/javieraviles/node-typescript-koa-rest/issues/39).
- Fix -> Logging levels were not correctly mapped. Thanks to @atamano for the PR [Pull Request 35](https://github.com/javieraviles/node-typescript-koa-rest/pull/35)
- Some code leftovers removed
### 1.4.1
- Fix -> After updating winston to 3.0.0, it was throwing an error when logging errors into file
- Fix -> Config in config.ts wasn't implementing IConfig interface
### 1.4.0
- Dotenv lib updated, no changes needed (they are dropping node4 support)
- Class-validator lib updated, no chages needed (cool features added like IsPhoneNumber or custom context for decorators)
- Winston lib updated to 3.0.0, some amendments needed to format the console log. Removed the @types as Winston now supports Typescript natively!
- Some devDependencies updated as well
### 1.3.0
- CORS added
- Syntax full REST
- Some error handling improvement
### 1.2.0
- Heroku deployment added
### 1.1.0
- Added Helmet for security
- Some bad practices await/async fixed

17
api/docker-compose.yml Normal file
View File

@ -0,0 +1,17 @@
version: '3.1'
services :
db:
image: postgres:13-alpine
ports:
- "5432:5432"
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: apidb
admin:
image: adminer
restart: always
depends_on:
- db
ports:
- 8080:8080

6852
api/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

61
api/package.json Normal file
View File

@ -0,0 +1,61 @@
{
"name": "virtual-phone-number-api",
"version": "0.0.1",
"description": "",
"main": "dist/server.js",
"scripts": {
"watch-server": "nodemon --ignore src/__tests__/ --watch src -e ts,tsx --exec ts-node src/server.ts",
"serve": "node dist/server.js",
"build": "tsc",
"start": "npm run serve",
"test": "jest",
"test:coverage": "jest --collect-coverage",
"test:watch": "jest --watch"
},
"engines": {
"node": ">=14",
"npm": ">=6"
},
"author": "Mokhtar Mial",
"license": "MIT",
"devDependencies": {
"@types/jest": "^26.0.23",
"@types/koa": "^2.13.2",
"@types/koa-bodyparser": "^4.3.0",
"@types/koa-helmet": "^6.0.2",
"@types/koa__router": "^8.0.4",
"@types/koa__cors": "^3.0.2",
"@types/node": "^14.17.1",
"jest": "^27.0.1",
"nodemon": "^2.0.7",
"ts-jest": "^27.0.1",
"ts-node": "^10.0.0",
"typescript": "^4.3.2"
},
"dependencies": {
"@koa/cors": "3.1.0",
"@koa/router": "10.0.0",
"@lifeomic/twilio-webhook-validator-koa": "^1.2.0",
"class-validator": "0.13.1",
"dotenv": "10.0.0",
"koa": "2.13.1",
"koa-bodyparser": "4.3.0",
"koa-helmet": "6.1.0",
"pg": "8.6.0",
"reflect-metadata": "0.1.13",
"twilio": "^3.63.0",
"typeorm": "0.2.32",
"winston": "3.3.3"
},
"jest": {
"roots": [
"<rootDir>"
],
"testMatch": [
"**/__tests__/**/*.+(ts|tsx|js)"
],
"transform": {
"^.+\\.(ts|tsx)$": "ts-jest"
}
}
}

View File

@ -0,0 +1,60 @@
import SmsController from "../../src/controller/sms";
import { Sms } from "../../src/entity/sms";
import { getManager } from "typeorm";
import { Context } from "koa";
import { ValidationError, validate } from "class-validator";
const sms: Sms = new Sms();
sms.id = 0;
sms.name = "John";
sms.name = "johndoe@gmail.com";
jest.mock("typeorm", () => {
const doNothing = () => {
//Empty function that mocks typeorm annotations
};
return {
getManager: jest.fn(),
PrimaryGeneratedColumn: doNothing,
Column: doNothing,
Entity: doNothing,
Equal: doNothing,
Not: doNothing,
Like: doNothing,
};
});
jest.mock("class-validator", () => {
const doNothing = () => {
//Empty function that mocks typeorm annotations
};
return {
validate: jest.fn(),
Length: doNothing,
IsEmail: doNothing,
};
});
describe("Sms controller", () => {
it("getUsers should return status 200 and found users.", async () => {
const userRepository = { find: jest.fn().mockReturnValue([sms]) };
(getManager as jest.Mock).mockReturnValue({ getRepository: () => userRepository });
const context = { status: undefined, body: undefined } as Context;
await SmsController.sendSms(context);
expect(userRepository.find).toHaveBeenCalledTimes(1);
expect(context.status).toBe(200);
expect(context.body).toStrictEqual([sms]);
});
it("createUser should return status 201 if is created.", async () => {
const userRepository = { save: jest.fn().mockReturnValue(sms), findOne: () => undefined as Sms };
(getManager as jest.Mock).mockReturnValue({ getRepository: () => userRepository });
(validate as jest.Mock).mockReturnValue([]);
const context = { status: undefined, body: undefined, request: { body: sms } } as unknown as Context;
await SmsController.receiveSms(context);
expect(userRepository.save).toHaveBeenCalledTimes(1);
expect(context.status).toBe(201);
expect(context.body).toStrictEqual(sms);
});
});

View File

@ -0,0 +1,9 @@
import { Sms } from "../../src/entity/user";
test("user", () => {
const user = new Sms();
user.name = "John Doe";
user.email = "johndoe@gmail.com";
expect(user.name).toBe("John Doe");
expect(user.email).toBe("johndoe@gmail.com");
});

20
api/src/config.ts Normal file
View File

@ -0,0 +1,20 @@
import dotenv from "dotenv";
dotenv.config({ path: ".env" });
const isDevMode = process.env.NODE_ENV == "development";
const config = {
port: +(process.env.PORT || 9029),
debugLogging: isDevMode,
databaseUrl: process.env.DATABASE_URL || "postgres://user:pass@localhost:5432/apidb",
dbEntitiesPath: [
...isDevMode ? ["src/entity/**/*.ts"] : ["dist/entity/**/*.js"],
],
twilio: {
accountSid: process.env.TWILIO_ACCOUNT_SID!,
authToken: process.env.TWILIO_AUTH_TOKEN!,
},
};
export default config;

View File

@ -0,0 +1,15 @@
import Router from "@koa/router";
import { Twilio, twiml } from "twilio";
import config from "../config";
const forwardTo = "+33613370787";
export default class CallController {
public static forwardCall: Router.Middleware = async (ctx) => {
const voiceResponse = new twiml.VoiceResponse()
voiceResponse.dial(forwardTo);
ctx.status = 200;
};
}

100
api/src/controller/sms.ts Normal file
View File

@ -0,0 +1,100 @@
import Router from "@koa/router";
import { Twilio } from "twilio";
import { getManager } from "typeorm";
import config from "../config";
import { Sms, SmsType } from "../entity/sms";
const client = new Twilio(config.twilio.accountSid, config.twilio.authToken);
const phoneNumber = "+33757592025";
// const from = "Mokhtar";
type Recipient = string;
export type Conversation = Record<Recipient, Sms[]>;
export default class SmsController {
public static getConversations: Router.Middleware = async (ctx) => {
const smsRepository = getManager().getRepository(Sms);
const messages = await smsRepository.find({
where: [
{ from: phoneNumber },
{ to: phoneNumber },
],
});
const conversations = messages.reduce<Conversation>((acc, message) => {
let recipient: string;
if (message.type === SmsType.SENT) {
recipient = message.to;
} else {
recipient = message.from;
}
if (!acc[recipient]) {
acc[recipient] = [];
}
acc[recipient].push(message);
return acc;
}, {});
ctx.body = conversations;
ctx.status = 200;
};
public static sendSms: Router.Middleware = async (ctx) => {
const smsRepository = getManager().getRepository(Sms);
const { to, content } = ctx.request.body;
await client.messages.create({ body: content, from: phoneNumber, to });
const sms = new Sms();
sms.type = SmsType.SENT;
sms.sentAt = new Date();
sms.content = content;
sms.to = to;
sms.from = phoneNumber;
await smsRepository.save(sms);
ctx.status = 200;
};
public static receiveSms: Router.Middleware = async (ctx) => {
const smsRepository = getManager().getRepository(Sms);
console.log("ctx.request.body", ctx.request.body);
const body: ReceivedSms = ctx.request.body;
console.log("body.From", body.From);
console.log("body.To", body.To);
console.log("body.Body", body.Body);
const sms = new Sms();
sms.type = SmsType.RECEIVED;
sms.sentAt = new Date();
sms.content = body.Body;
sms.to = body.To;
sms.from = body.From;
await smsRepository.save(sms);
ctx.status = 200;
ctx.body = undefined;
};
}
type ReceivedSms = {
ToCountry: string;
ToState: string;
SmsMessageSid: string;
NumMedia: string;
ToCity: string;
FromZip: string;
SmsSid: string;
FromState: string;
SmsStatus: string;
FromCity: string;
Body: string;
FromCountry: string;
To: string;
ToZip: string;
NumSegments: string;
MessageSid: string;
AccountSid: string;
From: string;
ApiVersion: string;
}

36
api/src/entity/sms.ts Normal file
View File

@ -0,0 +1,36 @@
import { Entity, Column, PrimaryGeneratedColumn, Index, CreateDateColumn } from "typeorm";
import { Length, IsPhoneNumber } from "class-validator";
export enum SmsType {
SENT = "sent",
RECEIVED = "received",
}
@Entity()
export class Sms {
@PrimaryGeneratedColumn()
id: number;
@Column("text")
@Length(1, 10000)
content: string;
@Index()
@Column("text")
@IsPhoneNumber()
from: string;
@Index()
@Column("text")
@IsPhoneNumber()
to: string;
@Column({
type: "enum",
enum: SmsType,
})
type: SmsType;
@CreateDateColumn()
sentAt: Date;
}

48
api/src/logger.ts Normal file
View File

@ -0,0 +1,48 @@
import type { Context, Middleware } from "koa";
import { transports, format } from "winston";
import path from "path";
import config from "./config";
const logger = (winstonInstance: typeof import("winston")): Middleware => {
winstonInstance.configure({
level: config.debugLogging ? "debug" : "info",
transports: [
// - Write all logs error (and below) to `error.log`.
new transports.File({ filename: path.resolve(__dirname, "../error.log"), level: "error" }),
// - Write to all logs with specified level to console.
new transports.Console({
format: format.combine(
format.colorize(),
format.simple(),
),
}),
],
});
return async (ctx: Context, next: () => Promise<any>): Promise<void> => {
const start = Date.now();
try {
await next();
} catch (err) {
ctx.status = err.status || 500;
ctx.body = err.message;
}
const ms = Date.now() - start;
let logLevel: string;
if (ctx.status >= 500) {
logLevel = "error";
} else if (ctx.status >= 400) {
logLevel = "warn";
} else {
logLevel = "info";
}
const msg = `${ctx.method} ${ctx.originalUrl} ${ctx.status} ${ms}ms`;
winstonInstance.log(logLevel, msg);
};
};
export default logger;

15
api/src/router.ts Normal file
View File

@ -0,0 +1,15 @@
import Router from "@koa/router";
import SmsController from "./controller/sms";
import CallController from "./controller/call";
import { webhookValidator } from "@lifeomic/twilio-webhook-validator-koa";
import config from "./config";
const router = new Router();
router.get("/conversations", SmsController.getConversations);
router.post("/send-sms", SmsController.sendSms);
router.post("/receive-sms", webhookValidator({ authToken: config.twilio.authToken, protocol: "https" }), SmsController.receiveSms);
router.post("/receive-call", webhookValidator({ authToken: config.twilio.authToken, protocol: "https" }), CallController.forwardCall);
export default router;

46
api/src/server.ts Normal file
View File

@ -0,0 +1,46 @@
import Koa from "koa";
import bodyParser from "koa-bodyparser";
import helmet from "koa-helmet";
import cors from "@koa/cors";
import winston from "winston";
import type { ConnectionOptions } from "typeorm";
import { createConnection } from "typeorm";
import "reflect-metadata";
import logger from "./logger";
import config from "./config";
import router from "./router";
const connectionOptions: ConnectionOptions = {
type: "postgres",
url: config.databaseUrl,
synchronize: true,
logging: false,
entities: config.dbEntitiesPath,
extra: {},
};
// create connection with database
// note that its not active database connection
// TypeORM creates you connection pull to uses connections from pull on your requests
createConnection(connectionOptions).then(async () => {
const app = new Koa();
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'", "cdnjs.cloudflare.com"],
styleSrc: ["'self'", "'unsafe-inline'", "cdnjs.cloudflare.com", "fonts.googleapis.com"],
fontSrc: ["'self'", "fonts.gstatic.com"],
imgSrc: ["'self'", "data:"],
},
}));
app.use(cors());
app.use(logger(winston));
app.use(bodyParser());
app.use(router.routes()).use(router.allowedMethods());
app.listen(config.port, () => {
console.log(`Server running on port ${config.port}`);
});
}).catch((error: string) => console.log("TypeORM connection error: ", error));

29
api/tsconfig.json Normal file
View File

@ -0,0 +1,29 @@
{
"compilerOptions": {
"target": "ES2017",
"module": "commonjs",
"lib": ["es6"],
"sourceMap": true,
"outDir": "dist",
"strict": true,
"strictPropertyInitialization": false,
"moduleResolution": "node",
"baseUrl": ".",
"paths": {
"*": [
"node_modules/*"
]
},
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipLibCheck": true
},
"include": [
"src/**/*"
],
"exclude": [
"src/__tests__"
]
}

View File

@ -0,0 +1,6 @@
{
"e997a5256149a4b76e6bfd6cbf519c5e5a0f1d278a3d8fa1253022b03c90473b": true,
"af683c96e0ffd2cf81287651c9433fa44debc1220ca7cb431fe482747f34a505": true,
"12bb71342c6255bbf50437ec8f4441c083f47cdb74bd89160c15e4f43e52a1cb": true,
"40b842e832070c58deac6aa9e08fa459302ee3f9da492c7e77d93d2fbf4a56fd": true
}

13
app/.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
node_modules/
.expo/
npm-debug.*
*.jks
*.p8
*.p12
*.key
*.mobileprovision
*.orig.*
web-build/
# macOS
.DS_Store

24
app/App.tsx Normal file
View File

@ -0,0 +1,24 @@
import "react-native-gesture-handler";
import { StatusBar } from "expo-status-bar";
import React from "react";
import { SafeAreaProvider } from "react-native-safe-area-context";
import useCachedResources from "./hooks/useCachedResources";
import useColorScheme from "./hooks/useColorScheme";
import Navigation from "./navigation";
export default function App() {
const isLoadingComplete = useCachedResources();
const colorScheme = useColorScheme();
if (!isLoadingComplete) {
return null;
} else {
return (
<SafeAreaProvider>
<Navigation colorScheme={colorScheme} />
<StatusBar />
</SafeAreaProvider>
);
}
}

34
app/app.json Normal file
View File

@ -0,0 +1,34 @@
{
"expo": {
"name": "virtual-phone",
"slug": "virtual-phone",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/images/icon.png",
"scheme": "myapp",
"userInterfaceStyle": "automatic",
"splash": {
"image": "./assets/images/splash.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
"updates": {
"fallbackToCacheTimeout": 0
},
"assetBundlePatterns": [
"**/*"
],
"ios": {
"supportsTablet": true
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/images/adaptive-icon.png",
"backgroundColor": "#ffffff"
}
},
"web": {
"favicon": "./assets/images/favicon.png"
}
}
}

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

BIN
app/assets/images/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

7
app/babel.config.js Normal file
View File

@ -0,0 +1,7 @@
module.exports = function (api) {
api.cache(true);
return {
presets: ["babel-preset-expo"],
plugins: ["react-native-reanimated/plugin"],
};
};

View File

@ -0,0 +1,80 @@
import * as WebBrowser from "expo-web-browser";
import React from "react";
import { StyleSheet, TouchableOpacity } from "react-native";
import Colors from "../constants/Colors";
import { MonoText } from "./StyledText";
import { Text, View } from "./Themed";
export default function EditScreenInfo({ path }: { path: string }) {
return (
<View>
<View style={styles.getStartedContainer}>
<Text
style={styles.getStartedText}
lightColor="rgba(0,0,0,0.8)"
darkColor="rgba(255,255,255,0.8)">
Open up the code for this screen:
</Text>
<View
style={[styles.codeHighlightContainer, styles.homeScreenFilename]}
darkColor="rgba(255,255,255,0.05)"
lightColor="rgba(0,0,0,0.05)">
<MonoText>{path}</MonoText>
</View>
<Text
style={styles.getStartedText}
lightColor="rgba(0,0,0,0.8)"
darkColor="rgba(255,255,255,0.8)">
Change any of the text, save the file, and your app will automatically update.
</Text>
</View>
<View style={styles.helpContainer}>
<TouchableOpacity onPress={handleHelpPress} style={styles.helpLink}>
<Text style={styles.helpLinkText} lightColor={Colors.light.tint}>
Tap here if your app doesn't automatically update after making changes
</Text>
</TouchableOpacity>
</View>
</View>
);
}
function handleHelpPress() {
WebBrowser.openBrowserAsync(
"https://docs.expo.io/get-started/create-a-new-app/#opening-the-app-on-your-phonetablet",
);
}
const styles = StyleSheet.create({
getStartedContainer: {
alignItems: "center",
marginHorizontal: 50,
},
homeScreenFilename: {
marginVertical: 7,
},
codeHighlightContainer: {
borderRadius: 3,
paddingHorizontal: 4,
},
getStartedText: {
fontSize: 17,
lineHeight: 24,
textAlign: "center",
},
helpContainer: {
marginTop: 15,
marginHorizontal: 20,
alignItems: "center",
},
helpLink: {
paddingVertical: 15,
},
helpLinkText: {
textAlign: "center",
},
});

View File

@ -0,0 +1,7 @@
import * as React from "react";
import { Text, TextProps } from "./Themed";
export function MonoText(props: TextProps) {
return <Text {...props} style={[props.style, { fontFamily: "space-mono" }]} />;
}

46
app/components/Themed.tsx Normal file
View File

@ -0,0 +1,46 @@
/**
* Learn more about Light and Dark modes:
* https://docs.expo.io/guides/color-schemes/
*/
import * as React from "react";
import { Text as DefaultText, View as DefaultView } from "react-native";
import Colors from "../constants/Colors";
import useColorScheme from "../hooks/useColorScheme";
export function useThemeColor(
props: { light?: string; dark?: string },
colorName: keyof typeof Colors.light & keyof typeof Colors.dark,
) {
const theme = useColorScheme();
const colorFromProps = props[theme];
if (colorFromProps) {
return colorFromProps;
} else {
return Colors[theme][colorName];
}
}
type ThemeProps = {
lightColor?: string;
darkColor?: string;
};
export type TextProps = ThemeProps & DefaultText["props"];
export type ViewProps = ThemeProps & DefaultView["props"];
export function Text(props: TextProps) {
const { style, lightColor, darkColor, ...otherProps } = props;
const color = useThemeColor({ light: lightColor, dark: darkColor }, "text");
return <DefaultText style={[{ color }, style]} {...otherProps} />;
}
export function View(props: ViewProps) {
const { style, lightColor, darkColor, ...otherProps } = props;
const backgroundColor = useThemeColor({ light: lightColor, dark: darkColor }, "background");
return <DefaultView style={[{ backgroundColor }, style]} {...otherProps} />;
}

View File

@ -0,0 +1,10 @@
import * as React from "react";
import renderer from "react-test-renderer";
import { MonoText } from "../StyledText";
it(`renders correctly`, () => {
const tree = renderer.create(<MonoText>Snapshot test!</MonoText>).toJSON();
expect(tree).toMatchSnapshot();
});

19
app/constants/Colors.ts Normal file
View File

@ -0,0 +1,19 @@
const tintColorLight = "#2f95dc";
const tintColorDark = "#fff";
export default {
light: {
text: "#000",
background: "#fff",
tint: tintColorLight,
tabIconDefault: "#ccc",
tabIconSelected: tintColorLight,
},
dark: {
text: "#fff",
background: "#000",
tint: tintColorDark,
tabIconDefault: "#ccc",
tabIconSelected: tintColorDark,
},
};

12
app/constants/Layout.ts Normal file
View File

@ -0,0 +1,12 @@
import { Dimensions } from "react-native";
const width = Dimensions.get("window").width;
const height = Dimensions.get("window").height;
export default {
window: {
width,
height,
},
isSmallDevice: width < 375,
};

View File

@ -0,0 +1,33 @@
import { Ionicons } from "@expo/vector-icons";
import * as Font from "expo-font";
import * as SplashScreen from "expo-splash-screen";
import * as React from "react";
export default function useCachedResources() {
const [isLoadingComplete, setLoadingComplete] = React.useState(false);
// Load any resources or data that we need prior to rendering the app
React.useEffect(() => {
async function loadResourcesAndDataAsync() {
try {
SplashScreen.preventAutoHideAsync();
// Load fonts
await Font.loadAsync({
...Ionicons.font,
"space-mono": require("../assets/fonts/SpaceMono-Regular.ttf"),
});
} catch (e) {
// We might want to provide this error information to an error reporting service
console.warn(e);
} finally {
setLoadingComplete(true);
SplashScreen.hideAsync();
}
}
loadResourcesAndDataAsync();
}, []);
return isLoadingComplete;
}

View File

@ -0,0 +1,8 @@
import { ColorSchemeName, useColorScheme as _useColorScheme } from "react-native";
// The useColorScheme value is always either light or dark, but the built-in
// type suggests that it can be null. This will not happen in practice, so this
// makes it a bit easier to work with.
export default function useColorScheme(): NonNullable<ColorSchemeName> {
return _useColorScheme() as NonNullable<ColorSchemeName>;
}

View File

@ -0,0 +1,78 @@
/**
* Learn more about createBottomTabNavigator:
* https://reactnavigation.org/docs/bottom-tab-navigator
*/
import { Ionicons } from "@expo/vector-icons";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { createStackNavigator } from "@react-navigation/stack";
import * as React from "react";
import Colors from "../constants/Colors";
import useColorScheme from "../hooks/useColorScheme";
import TabOneScreen from "../screens/TabOneScreen";
import TabTwoScreen from "../screens/TabTwoScreen";
import { BottomTabParamList, TabOneParamList, TabTwoParamList } from "../types";
const BottomTab = createBottomTabNavigator<BottomTabParamList>();
export default function BottomTabNavigator() {
const colorScheme = useColorScheme();
return (
<BottomTab.Navigator
initialRouteName="TabOne"
tabBarOptions={{ activeTintColor: Colors[colorScheme].tint }}>
<BottomTab.Screen
name="TabOne"
component={TabOneNavigator}
options={{
tabBarIcon: ({ color }) => <TabBarIcon name="ios-code" color={color} />,
}}
/>
<BottomTab.Screen
name="TabTwo"
component={TabTwoNavigator}
options={{
tabBarIcon: ({ color }) => <TabBarIcon name="ios-code" color={color} />,
}}
/>
</BottomTab.Navigator>
);
}
// You can explore the built-in icon families and icons on the web at:
// https://icons.expo.fyi/
function TabBarIcon(props: { name: React.ComponentProps<typeof Ionicons>["name"]; color: string }) {
return <Ionicons size={30} style={{ marginBottom: -3 }} {...props} />;
}
// Each tab has its own navigation stack, you can read more about this pattern here:
// https://reactnavigation.org/docs/tab-based-navigation#a-stack-navigator-for-each-tab
const TabOneStack = createStackNavigator<TabOneParamList>();
function TabOneNavigator() {
return (
<TabOneStack.Navigator>
<TabOneStack.Screen
name="TabOneScreen"
component={TabOneScreen}
options={{ headerTitle: "Tab One Title" }}
/>
</TabOneStack.Navigator>
);
}
const TabTwoStack = createStackNavigator<TabTwoParamList>();
function TabTwoNavigator() {
return (
<TabTwoStack.Navigator>
<TabTwoStack.Screen
name="TabTwoScreen"
component={TabTwoScreen}
options={{ headerTitle: "Tab Two Title" }}
/>
</TabTwoStack.Navigator>
);
}

View File

@ -0,0 +1,30 @@
/**
* Learn more about deep linking with React Navigation
* https://reactnavigation.org/docs/deep-linking
* https://reactnavigation.org/docs/configuring-links
*/
import * as Linking from "expo-linking";
export default {
prefixes: [Linking.makeUrl("/")],
config: {
screens: {
Root: {
screens: {
TabOne: {
screens: {
TabOneScreen: "one",
},
},
TabTwo: {
screens: {
TabTwoScreen: "two",
},
},
},
},
NotFound: "*",
},
},
};

37
app/navigation/index.tsx Normal file
View File

@ -0,0 +1,37 @@
/**
* If you are not familiar with React Navigation, check out the "Fundamentals" guide:
* https://reactnavigation.org/docs/getting-started
*
*/
import { NavigationContainer, DefaultTheme, DarkTheme } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import * as React from "react";
import { ColorSchemeName } from "react-native";
import NotFoundScreen from "../screens/NotFoundScreen";
import { RootStackParamList } from "../types";
import BottomTabNavigator from "./BottomTabNavigator";
import LinkingConfiguration from "./LinkingConfiguration";
export default function Navigation({ colorScheme }: { colorScheme: ColorSchemeName }) {
return (
<NavigationContainer
linking={LinkingConfiguration}
theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}>
<RootNavigator />
</NavigationContainer>
);
}
// A root stack navigator is often used for displaying modals on top of all other content
// Read more here: https://reactnavigation.org/docs/modal
const Stack = createStackNavigator<RootStackParamList>();
function RootNavigator() {
return (
<Stack.Navigator screenOptions={{ headerShown: false }}>
<Stack.Screen name="Root" component={BottomTabNavigator} />
<Stack.Screen name="NotFound" component={NotFoundScreen} options={{ title: "Oops!" }} />
</Stack.Navigator>
);
}

15458
app/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

45
app/package.json Normal file
View File

@ -0,0 +1,45 @@
{
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"eject": "expo eject",
"test": "jest --watchAll"
},
"jest": {
"preset": "jest-expo"
},
"dependencies": {
"@expo/vector-icons": "12.0.5",
"@react-native-community/masked-view": "0.1.11",
"@react-navigation/bottom-tabs": "5.11.11",
"@react-navigation/native": "5.9.4",
"@react-navigation/stack": "5.14.5",
"expo": "41.0.1",
"expo-asset": "8.3.2",
"expo-constants": "10.1.3",
"expo-font": "9.1.0",
"expo-linking": "2.2.3",
"expo-splash-screen": "0.10.2",
"expo-status-bar": "1.0.4",
"expo-web-browser": "9.1.0",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-native": "https://github.com/expo/react-native/archive/sdk-41.0.0.tar.gz",
"react-native-reanimated": "2.2.0",
"react-native-gesture-handler": "1.10.3",
"react-native-safe-area-context": "3.2.0",
"react-native-screens": "3.3.0",
"react-native-web": "0.16.3"
},
"devDependencies": {
"@babel/core": "7.14.3",
"@types/react": "17.0.8",
"@types/react-native": "0.64.8",
"jest-expo": "41.0.0",
"typescript": "4.3.2"
},
"private": true
}

View File

@ -0,0 +1,40 @@
import { StackScreenProps } from "@react-navigation/stack";
import * as React from "react";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { RootStackParamList } from "../types";
export default function NotFoundScreen({
navigation,
}: StackScreenProps<RootStackParamList, "NotFound">) {
return (
<View style={styles.container}>
<Text style={styles.title}>This screen doesn't exist.</Text>
<TouchableOpacity onPress={() => navigation.replace("Root")} style={styles.link}>
<Text style={styles.linkText}>Go to home screen!</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
padding: 20,
},
title: {
fontSize: 20,
fontWeight: "bold",
},
link: {
marginTop: 15,
paddingVertical: 15,
},
linkText: {
fontSize: 14,
color: "#2e78b7",
},
});

View File

@ -0,0 +1,32 @@
import * as React from "react";
import { StyleSheet } from "react-native";
import EditScreenInfo from "../components/EditScreenInfo";
import { Text, View } from "../components/Themed";
export default function TabOneScreen() {
return (
<View style={styles.container}>
<Text style={styles.title}>Tab One</Text>
<View style={styles.separator} lightColor="#eee" darkColor="rgba(255,255,255,0.1)" />
<EditScreenInfo path="/screens/TabOneScreen.tsx" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
title: {
fontSize: 20,
fontWeight: "bold",
},
separator: {
marginVertical: 30,
height: 1,
width: "80%",
},
});

View File

@ -0,0 +1,57 @@
import * as React from "react";
import { StyleSheet } from "react-native";
import EditScreenInfo from "../components/EditScreenInfo";
import { Text, View } from "../components/Themed";
import type { Conversation } from "../../api/src/controller/sms";
export default function TabTwoScreen() {
const [conversations, setConversations] = React.useState<Conversation>({});
const conversationsEntries = Object.entries(conversations);
React.useEffect(() => {
fetch("http://192.168.1.40:3000/conversations")
.then(response => response.json())
.then(conversations => setConversations(conversations))
.catch(error => console.error("error", error));
}, []);
return (
<View style={styles.container}>
<Text style={styles.title}>Tab Two</Text>
<View style={styles.separator} lightColor="#eee" darkColor="rgba(255,255,255,0.1)" />
{conversationsEntries.map(([recipient, messages], index) => {
const lastMessage = messages[messages.length - 1];
return (
<>
<View>
<Text>{recipient}</Text>
<Text>{lastMessage.content}</Text>
<Text>{new Date(lastMessage.sentAt).toDateString()}</Text>
</View>
{index + 1 < messages.length && (
<View style={styles.separator} lightColor="#eee" darkColor="rgba(255,255,255,0.1)" />
)}
</>
)
})}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
title: {
fontSize: 20,
fontWeight: "bold",
},
separator: {
marginVertical: 30,
height: 1,
width: "80%",
},
});

6
app/tsconfig.json Normal file
View File

@ -0,0 +1,6 @@
{
"extends": "expo/tsconfig.base",
"compilerOptions": {
"strict": true
}
}

22
app/types.tsx Normal file
View File

@ -0,0 +1,22 @@
/**
* Learn more about using TypeScript with React Navigation:
* https://reactnavigation.org/docs/typescript/
*/
export type RootStackParamList = {
Root: undefined;
NotFound: undefined;
};
export type BottomTabParamList = {
TabOne: undefined;
TabTwo: undefined;
};
export type TabOneParamList = {
TabOneScreen: undefined;
};
export type TabTwoParamList = {
TabTwoScreen: undefined;
};