GithubHelp home page GithubHelp logo

w3tecch / express-typescript-boilerplate Goto Github PK

View Code? Open in Web Editor NEW
3.2K 3.2K 895.0 1.88 MB

A delightful way to building a RESTful API with NodeJs & TypeScript by @w3tecch

License: MIT License

JavaScript 11.23% TypeScript 86.82% Dockerfile 0.31% Shell 1.65%
annotations boilerplate database documentation e2e-tests express-typescript-boilerplate expressjs ioc jest migrations monitoring nodejs restful-api seed seeding skeleton starter-kit typescript validation

express-typescript-boilerplate's Introduction

w3tec

Express Typescript Boilerplate

dependency travis appveyor StackShare

A delightful way to building a Node.js RESTful API Services with beautiful code written in TypeScript.
Inspired by the awesome framework laravel in PHP and of the repositories from pleerock
Made with ❤️ by w3tech, Gery Hirschfeld and contributors


divider

❯ Why

Our main goal with this project is a feature complete server application. We like you to be focused on your business and not spending hours in project configuration.

Try it!! We are happy to hear your feedback or any kind of new features.

Features

  • Beautiful Code thanks to the awesome annotations of the libraries from pleerock.
  • Easy API Testing with included e2e testing.
  • Dependency Injection done with the nice framework from TypeDI.
  • Simplified Database Query with the ORM TypeORM.
  • Clear Structure with different layers such as controllers, services, repositories, models, middlewares...
  • Easy Exception Handling thanks to routing-controllers.
  • Smart Validation thanks to class-validator with some nice annotations.
  • Custom Validators to validate your request even better and stricter. custom-validation-classes.
  • API Documentation thanks to swagger and routing-controllers-openapi.
  • API Monitoring thanks to express-status-monitor.
  • Integrated Testing Tool thanks to Jest.
  • E2E API Testing thanks to supertest.
  • Basic Security Features thanks to Helmet.
  • Easy event dispatching thanks to event-dispatch.
  • Fast Database Building with simple migration from TypeORM.
  • Easy Data Seeding with our own factories.
  • GraphQL provides as a awesome query language for our api GraphQL.
  • TypeGraphQL thanks to TypeGraphQL we have a some cool decorators to simplify the usage of GraphQL.
  • DataLoaders helps with performance thanks to caching and batching DataLoaders.

divider

❯ Table of Contents

divider

❯ Getting Started

Step 1: Set up the Development Environment

You need to set up your development environment before you can do anything.

Install Node.js and NPM

Install yarn globally

yarn global add yarn

Install a MySQL database.

If you work with a mac, we recommend to use homebrew for the installation.

Step 2: Create new Project

Fork or download this project. Configure your package.json for your new project.

Then copy the .env.example file and rename it to .env. In this file you have to add your database connection information.

Create a new database with the name you have in your .env-file.

Then setup your application environment.

yarn run setup

This installs all dependencies with yarn. After that it migrates the database and seeds some test data into it. So after that your development environment is ready to use.

Step 3: Serve your App

Go to the project dir and start your app with this yarn script.

yarn start serve

This starts a local server using nodemon, which will watch for any file changes and will restart the server according to these changes. The server address will be displayed to you as http://0.0.0.0:3000.

divider

❯ Scripts and Tasks

All script are defined in the package-scripts.js file, but the most important ones are listed here.

Install

  • Install all dependencies with yarn install

Linting

  • Run code quality analysis using yarn start lint. This runs tslint.
  • There is also a vscode task for this called lint.

Tests

  • Run the unit tests using yarn start test (There is also a vscode task for this called test).
  • Run the integration tests using yarn start test.integration.
  • Run the e2e tests using yarn start test.e2e.

Running in dev mode

  • Run yarn start serve to start nodemon with ts-node, to serve the app.
  • The server address will be displayed to you as http://0.0.0.0:3000

Building the project and run it

  • Run yarn start build to generated all JavaScript files from the TypeScript sources (There is also a vscode task for this called build).
  • To start the builded app located in dist use yarn start.

Database Migration

  • Run typeorm migration:create -n <migration-file-name> to create a new migration file.
  • Try typeorm -h to see more useful cli commands like generating migration out of your models.
  • To migrate your database run yarn start db.migrate.
  • To revert your latest migration run yarn start db.revert.
  • Drops the complete database schema yarn start db.drop.

Database Seeding

  • Run yarn start db.seed to seed your seeds into the database.

divider

❯ Debugger in VSCode

To debug your code run yarn start build or hit cmd + b to build your app. Then, just set a breakpoint and hit F5 in your Visual Studio Code.

divider

❯ API Routes

The route prefix is /api by default, but you can change this in the .env file. The swagger and the monitor route can be altered in the .env file.

Route Description
/api Shows us the name, description and the version of the package.json
/graphql Route to the graphql editor or your query/mutations requests
/swagger This is the Swagger UI with our API documentation
/monitor Shows a small monitor page for the server
/api/users Example entity endpoint
/api/pets Example entity endpoint

divider

❯ Project Structure

Name Description
.vscode/ VSCode tasks, launch configuration and some other settings
dist/ Compiled source files will be placed here
src/ Source files
src/api/controllers/ REST API Controllers
src/api/controllers/requests Request classes with validation rules if the body is not equal with a model
src/api/controllers/responses Response classes or interfaces to type json response bodies
src/api/errors/ Custom HttpErrors like 404 NotFound
src/api/interceptors/ Interceptors are used to change or replace the data returned to the client.
src/api/middlewares/ Express Middlewares like helmet security features
src/api/models/ TypeORM Models
src/api/repositories/ Repository / DB layer
src/api/services/ Service layer
src/api/subscribers/ Event subscribers
src/api/validators/ Custom validators, which can be used in the request classes
src/api/resolvers/ GraphQL resolvers (query, mutation & field-resolver)
src/api/types/ GraphQL types ,input-types and scalar types
src/api/ schema.gql Generated GraphQL schema
src/auth/ Authentication checkers and services
src/core/ The core features like logger and env variables
src/database/factories Factory the generate fake entities
src/database/migrations Database migration scripts
src/database/seeds Seeds to create some data in the database
src/decorators/ Custom decorators like @Logger & @EventDispatch
src/loaders/ Loader is a place where you can configure your app
src/public/ Static assets (fonts, css, js, img).
src/types/ *.d.ts Custom type definitions and files that aren't on DefinitelyTyped
test Tests
test/e2e/ *.test.ts End-2-End tests (like e2e)
test/integration/ *.test.ts Integration test with SQLite3
test/unit/ *.test.ts Unit tests
.env.example Environment configurations
.env.test Test environment configurations
mydb.sql SQLite database for integration tests. Ignored by git and only available after integration tests

divider

❯ Logging

Our logger is winston. To log http request we use the express middleware morgan. We created a simple annotation to inject the logger in your service (see example below).

import { Logger, LoggerInterface } from '../../decorators/Logger';

@Service()
export class UserService {

    constructor(
        @Logger(__filename) private log: LoggerInterface
    ) { }

    ...

divider

❯ Event Dispatching

We use this awesome repository event-dispatch for event dispatching. We created a simple annotation to inject the EventDispatcher in your service (see example below). All events are listed in the events.ts file.

import { events } from '../subscribers/events';
import { EventDispatcher, EventDispatcherInterface } from '../../decorators/EventDispatcher';

@Service()
export class UserService {

    constructor(
        @EventDispatcher() private eventDispatcher: EventDispatcherInterface
    ) { }

    public async create(user: User): Promise<User> {
        ...
        this.eventDispatcher.dispatch(events.user.created, newUser);
        ...
    }

divider

❯ Seeding

Isn't it exhausting to create some sample data for your database, well this time is over!

How does it work? Just create a factory for your entities (models) and a seed script.

1. Create a factory for your entity

For all entities we want to seed, we need to define a factory. To do so we give you the awesome faker library as a parameter into your factory. Then create your "fake" entity and return it. Those factory files should be in the src/database/factories folder and suffixed with Factory like src/database/factories/UserFactory.ts.

Settings can be used to pass some static value into the factory.

define(User, (faker: typeof Faker, settings: { roles: string[] }) => {
    const gender = faker.random.number(1);
    const firstName = faker.name.firstName(gender);
    const lastName = faker.name.lastName(gender);
    const email = faker.internet.email(firstName, lastName);

    const user = new User();
    user.firstName = firstName;
    user.lastName = lastName;
    user.email = email;
    user.roles = settings.roles;
    return user;
});

Handle relation in the entity factory like this.

define(Pet, (faker: typeof Faker, settings: undefined) => {
    const gender = faker.random.number(1);
    const name = faker.name.firstName(gender);

    const pet = new Pet();
    pet.name = name;
    pet.age = faker.random.number();
    pet.user = factory(User)({ roles: ['admin'] })
    return pet;
});

2. Create a seed file

The seeds files define how much and how the data are connected with each other. The files will be executed alphabetically. With the second function, accepting your settings defined in the factories, you are able to create different variations of entities.

export class CreateUsers implements Seed {

    public async seed(factory: Factory, connection: Connection): Promise<any> {
        await factory(User)({ roles: [] }).createMany(10);
    }

}

Here an example with nested factories. You can use the .map() function to alter the generated value before they get persisted.

...
await factory(User)()
    .map(async (user: User) => {
        const pets: Pet[] = await factory(Pet)().createMany(2);
        const petIds = pets.map((pet: Pet) => pet.Id);
        await user.pets().attach(petIds);
    })
    .createMany(5);
...

To deal with relations you can use the entity manager like this.

export class CreatePets implements SeedsInterface {

    public async seed(factory: FactoryInterface, connection: Connection): Promise<any> {
        const connection = await factory.getConnection();
        const em = connection.createEntityManager();

        await times(10, async (n) => {
            // This creates a pet in the database
            const pet = await factory(Pet)().create();
            // This only returns a entity with fake data
            const user = await factory(User)({ roles: ['admin'] }).make();
            user.pets = [pet];
            await em.save(user);
        });
    }

}

3. Run the seeder

The last step is the easiest, just hit the following command in your terminal, but be sure you are in the projects root folder.

yarn start db.seed

CLI Interface

Command Description
yarn start "db.seed" Run all seeds
yarn start "db.seed --run CreateBruce,CreatePets" Run specific seeds (file names without extension)
yarn start "db.seed -L" Log database queries to the terminal
yarn start "db.seed --factories <path>" Add a different path to your factories (Default: src/database/)
yarn start "db.seed --seeds <path>" Add a different path to your seeds (Default: src/database/seeds/)

divider

❯ GraphQL

For the GraphQL part we used the library TypeGraphQL to build awesome GraphQL API's.

The context(shown below) of the GraphQL is builded in the graphqlLoader.ts file. Inside of this loader we create a scoped container for each incoming request.

export interface Context {
  requestId: number;
  request: express.Request;
  response: express.Response;
  container: ContainerInstance;
}

DataLoader

For the usage of the DataLoaders we created a annotation, which automatically creates and registers a new DataLoader to the scoped container.

Here is an example of the PetResolver.

import DataLoader from 'dataloader';
import { DLoader } from '../../decorators/DLoader';
    ...
    constructor(
        private petService: PetService,
        @Logger(__filename) private log: LoggerInterface,
        @DLoader(UserModel) private userLoader: DataLoader<string, UserModel>
    ) { }
    ...

Or you could use the repository too.

@DLoader(UserRepository) private userLoader: DataLoader<string, UserModel>

Or even use a custom method of your given repository.

@DLoader(PetRepository, {
    method: 'findByUserIds',
    key: 'userId',
    multiple: true,
}) private petLoader: DataLoader<string, PetModel>

❯ Docker

Install Docker

Before you start, make sure you have a recent version of Docker installed

Build Docker image

docker build -t <your-image-name> .

Run Docker image in container and map port

The port which runs your application inside Docker container is either configured as PORT property in your .env configuration file or passed to Docker container via environment variable PORT. Default port is 3000.

Run image in detached mode

docker run -d -p <port-on-host>:<port-inside-docker-container> <your-image-name>

Run image in foreground mode

docker run -i -t -p <port-on-host>:<port-inside-docker-container> <your-image-name>

Stop Docker container

Detached mode

docker stop <container-id>

You can get a list of all running Docker container and its ids by following command

docker images

Foreground mode

Go to console and press + C at any time.

Docker environment variables

There are several options to configure your app inside a Docker container

project .env file

You can use .env file in project root folder which will be copied inside Docker image. If you want to change a property inside .env you have to rebuild your Docker image.

run options

You can also change app configuration by passing environment variables via docker run option -e or --env.

docker run --env DB_HOST=localhost -e DB_PORT=3306

environment file

Last but not least you can pass a config file to docker run.

docker run --env-file ./env.list

env.list example:

# this is a comment
DB_TYPE=mysql
DB_HOST=localhost
DB_PORT=3306

divider

❯ Further Documentations

Name & Link Description
Express Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
Microframework Microframework is a simple tool that allows you to execute your modules in a proper order, helping you to organize bootstrap code in your application.
TypeDI Dependency Injection for TypeScript.
routing-controllers Create structured, declarative and beautifully organized class-based controllers with heavy decorators usage in Express / Koa using TypeScript and Routing Controllers Framework.
TypeORM TypeORM is highly influenced by other ORMs, such as Hibernate, Doctrine and Entity Framework.
class-validator Validation made easy using TypeScript decorators.
class-transformer Proper decorator-based transformation / serialization / deserialization of plain javascript objects to class constructors
 event-dispatcher Dispatching and listening for application events in Typescript 
 Helmet Helmet helps you secure your Express apps by setting various HTTP headers. It’s not a silver bullet, but it can help! 
 Auth0 API Documentation Authentification service 
 Jest Delightful JavaScript Testing Library for unit and e2e tests 
 supertest Super-agent driven library for testing node.js HTTP servers using a fluent API 
 nock HTTP mocking and expectations library 
swagger Documentation   API Tool to describe and document your api.
SQLite Documentation  Getting Started with SQLite3 – Basic Commands.
GraphQL Documentation  A query language for your API.
DataLoader Documentation  DataLoader is a generic utility to be used as part of your application's data fetching layer to provide a consistent API over various backends and reduce requests to those backends via batching and caching.

divider

❯ Related Projects

divider

❯ License

MIT

express-typescript-boilerplate's People

Contributors

alber70g avatar chsch911028 avatar djro avatar dweber019 avatar et avatar gonza-lito avatar gualtierim avatar imanabu avatar itsemirhanengin avatar kristemmerman avatar larisartorisr avatar lopezm94 avatar maximzinovik avatar prog-rajkamal avatar solt9029 avatar tyderion avatar tyderion-snippets avatar vishnu-kyatannawar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

express-typescript-boilerplate's Issues

Creating resource with make:resource overwrites Targets

OS: Windows 10
Version: newest master (2.0.0-beta.2)

Description
When I create a new resource it overwrites the Targets.ts file removing all existing entries and not adding new ones.

Steps to reproduce

  • npm run console make:resource
  • Follow wizard, say yes to everything
  • At one point it asks Override "src/undefined"?

Result
It creates a new file
File created in: C:\Users\Archie\Documents\Coding\Anime-Loader\crawler-v2\src\constants/Targets.ts

Expected
I expected the script to update the Targets not overwrite them (thus removing the User constants) as well as adding constants for the new resource

Log

File created in: <path>\src\database\migrations\20170606114339_create_anime_table.ts
File created in: <path>\src\api\models\Anime.ts
File created in: <path>\src\types\resources\anime.d.ts
File created in: <path>\src\api\repositories\AnimeRepository.ts
File created in: <path>\src\api\services\AnimeService.ts
File created in: <path>\src\api\controllers\AnimeController.ts
File created in: <path>\src\api\requests\AnimeCreateRequest.ts
File created in: <path>\src\api\requests\AnimeUpdateRequest.ts
File created in: <path>\test\black-box\Anime.ts

? Update IoC targets? Yes
? Override "src/undefined"? Yes
File created in: <path>\src\constants/Targets.ts

Error after execute "npm run setup"

I'm obtaining an error after executing the "npm run setup" command:

root@api-express:/usr/src/app# npm run setup

[email protected] presetup /usr/src/app
yarn install

yarn install v1.3.2
[1/5] Validating package.json...
[2/5] Resolving packages...
success Already up-to-date.
Done in 0.94s.

[email protected] setup /usr/src/app
npm start setup.db
[email protected] start /usr/src/app
nps "setup.db"
nps is executing setup.db : nps db.migrate && nps db.seed
nps is executing db.migrate : nps banner.migrate && nps config && ts-node -F ./node_modules/typeorm/cli.js migrations:run
nps is executing banner.migrate : ts-node -F ./commands/banner.ts migrate
/bin/sh: 1: ts-node: not found
The script called "banner.migrate" which runs "ts-node -F ./commands/banner.ts migrate" failed with exit code 127 https://github.com/kentcdodds/nps/blob/v5.7.1/other/ERRORS_AND_WARNINGS.md#failed-with-exit-code
The script called "db.migrate" which runs "nps banner.migrate && nps config && ts-node -F ./node_modules/typeorm/cli.js migrations:run" failed with exit code 127 https://github.com/kentcdodds/nps/blob/v5.7.1/other/ERRORS_AND_WARNINGS.md#failed-with-exit-code
The script called "setup.db" which runs "nps db.migrate && nps db.seed" failed with exit code 127 https://github.com/kentcdodds/nps/blob/v5.7.1/other/ERRORS_AND_WARNINGS.md#failed-with-exit-code
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! [email protected] start: nps "setup.db"
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2018-01-22T06_26_48_050Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] setup: `npm start setup.db`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] setup script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2018-01-22T06_26_48_069Z-debug.log

Even, I had to install nps and typeorm globally, before this error. Any glue?

My .env file is this:

`

APPLICATION

APP_NAME="coin-sparta-api"
APP_ROUTE="http://localhost:3000"
APP_ROUTE_PREFIX="/api"
APP_BANNER=false

LOGGING

LOG_LEVEL="warning"
LOG_JSON=false
LOG_OUTPUT="dev"

AUTHORIZATION

AUTH_ROUTE="http://localhost:3333/tokeninfo"

DATABASE

DB_TYPE="mongodb"
DB_HOST=mongodb
DB_PORT=27017
DB_DATABASE="coinsparta"
DB_LOGGING=false

GraphQL

GRAPHQL_ENABLED=true
GRAPHQL_ROUTE="/graphql"

Swagger

SWAGGER_ENABLED=true
SWAGGER_ROUTE="/swagger"
SWAGGER_FILE="api/swagger.json"
SWAGGER_USERNAME="admin"
SWAGGER_PASSWORD="1234"

Status Monitor

MONITOR_ENABLED=true
MONITOR_ROUTE="/monitor"
MONITOR_USERNAME="admin"
MONITOR_PASSWORD="1234"
`

Question: How to make query with relation between pets and users

Thank you for the nice repository.
I managed to have the pets created and they are also exposed to the api after creating a middleware for it.
My question is probably very simple, but I am struggling with the code.

How can I now manage to make a query which pets belong to a user? And what is the best way to accomplish it (creating a new controller "userpets" or simply adding a fetchPetsByUserId() into the User.ts)?
How and where can I use the method user() which was inserted in the Pet.ts?

I would appreciate if you could add this as an example.

With best regards
foxthefox

the bug #60 not solved in rc.2

Hello,

Thanks for help to solve the #60 but again in the rc.2 same error....

> [email protected] setup /Users/far-paul/Sites/lucy/outilSL/server2
> npm start setup.db


> [email protected] start /Users/far-paul/Sites/lucy/outilSL/server2
> nps "setup.db"

Scripts must resolve to strings. There is no script that can be resolved from "setup.db" https://github.com/kentcdodds/nps/blob/v5.7.1/other/ERRORS_AND_WARNINGS.md#missing-script
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `nps "setup.db"`

Thanks

Plugin 'inversify-express-utils' error

I have an issue with running the build on Windows 10.

I get the following error : error: [core:Bootstrap] No matching bindings found for serviceIdentifier: Symbol(Controller), when running "npm start". I tried it on versions 2.0.0-beta and 1.7.0.

If I comment this line inversifyExpressServer.build() in Bootstrap.ts, then i can run it. But it doesn't hit the users controller.

npm --version: 5.0.4
node --version: v6.11.0
yarn --version: 0.27.5

Is this a known issue, or is it just me?

VSCode debug task doesn't work

When I try to run it I get Attribute 'program' does not exist ('/Users/simone/Documents/workspace/express-typescript-boilerplate/src/app.js.js').

Changing the path of program from src/ to dist/ seems to fix it

error with the last ts-node (^4.1.0) in setup

Hello,

Have errors with the last ts-node version :
"ts-node": "^4.1.0",

Not want to setup.

> [email protected] start /Users/far-paul/Sites/printaplus/express-typescript-boilerplate
> nps "setup.db"

nps is executing `setup.db` : nps db.migrate && nps db.seed
nps is executing `db.migrate` : nps banner.migrate && nps config && ts-node -F ./node_modules/typeorm/cli.js migrations:run
nps is executing `banner.migrate` : ts-node -F ./commands/banner.ts migrate
Error: Cannot find module '/Users/far-paul/Sites/printaplus/express-typescript-boilerplate/migrate'
    at Function.Module._resolveFilename (module.js:538:15)
    at Function.Module._load (module.js:468:25)
    at Function.Module.runMain (module.js:684:10)
    at Object.<anonymous> (/Users/far-paul/Sites/printaplus/express-typescript-boilerplate/node_modules/ts-node/src/_bin.ts:177:12)
    at Module._compile (module.js:643:30)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Function.Module.runMain (module.js:684:10)
The script called "banner.migrate" which runs "ts-node -F ./commands/banner.ts migrate" failed with exit code 1 https://github.com/kentcdodds/nps/blob/v5.7.1/other/ERRORS_AND_WARNINGS.md#failed-with-exit-code
The script called "db.migrate" which runs "nps banner.migrate && nps config && ts-node -F ./node_modules/typeorm/cli.js migrations:run" failed withexit code 1 https://github.com/kentcdodds/nps/blob/v5.7.1/other/ERRORS_AND_WARNINGS.md#failed-with-exit-code
The script called "setup.db" which runs "nps db.migrate && nps db.seed" failed with exit code 1 https://github.com/kentcdodds/nps/blob/v5.7.1/other/ERRORS_AND_WARNINGS.md#failed-with-exit-code
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `nps "setup.db"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/far-paul/.npm/_logs/2018-02-18T09_13_27_413Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] setup: `npm start setup.db`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] setup script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/far-paul/.npm/_logs/2018-02-18T09_13_27_437Z-debug.log

Thanks

normalizePort method in Server class is typed to accept only strings as parameters

normalizePort of core.Server only accepts strings as parameters. It is used in the core.Bootstrap class in the defineExpressApp method and passes a number as a parameter.

// ./src/core/Server.ts
export class Server {

    /**
     * Normalize port for the express application
     */
    public static normalizePort(port: string): number | string | boolean {
        const parsedPort = parseInt(port, 10);
        if (isNaN(parsedPort)) { // named pipe
            return port;
        }
        if (parsedPort >= 0) { // port number
            return parsedPort;
        }
        return false;
    }

  // ...
}

// ./src/core/Bootstrap.ts
export class Bootstrap {

    public log: Logger = new Logger(__filename);

    public defineExpressApp(app: express.Application): express.Application {
        app.set('host', process.env.APP_HOST);
        app.set('port', Server.normalizePort(process.env.PORT || process.env.APP_PORT || 3000));
        return app;
    }
  // ...
}

Unable to Get New Resouce in Swagger and Rest Client

Hi

I have created on Resource Product and I have got the all file which is container but after that I have run the npm run serve. command but still my apis is un-access able. It returning 404. Swagger also does not update for that tables.

I have add the following entry after resource file:

a) Targets.ts add Model, Controller,etc.
b) Tables.ts.

Can any one help me how to access new created Resource ?

Unable to Run on Ubuntu

Hi

I am unable to start project on Ubuntu system.

/home/charnjeet/node_modules/knex/lib/client.js:108
throw new Error('knex: Required configuration option 'client' is missing.');
^
Error: knex: Required configuration option 'client' is missing.
at new Client (/home/edl/git/ofs/poc/TsRestPOC/node_modules/knex/lib/client.js:108:11)
at Knex (/home/edl/git/ofs/poc/TsRestPOC/node_modules/knex/lib/index.js:60:34)
at Object.exports.Knex (/home/edl/git/ofs/poc/TsRestPOC/src/config/Database.ts:31:33)
at Object. (/home/edl/git/ofs/poc/TsRestPOC/src/config/Database.ts:33:47)
at Module._compile (module.js:571:32)
at Module.m._compile (/home/edl/git/ofs/poc/TsRestPOC/node_modules/ts-node/src/index.ts:392:23)
at Module._extensions..js (module.js:580:10)
at Object.require.extensions.(anonymous function) [as .ts] (/home/edl/git/ofs/poc/TsRestPOC/node_modules/ts-node/src/index.ts:395:12)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object. (/home/edl/git/ofs/poc/TsRestPOC/knexfile.ts:7:18)
at Module._compile (module.js:571:32)
at Module.m._compile (/home/edl/git/ofs/poc/TsRestPOC/node_modules/ts-node/src/index.ts:392:23)

Windows - broken setup/serve scripts

Some scripts from the package.json do not work correctly on windows machines.

for example, when I run npm run setup there is an error when executing knex:

C:\path\to\project\node_modules\.bin\knex:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
          ^^^^^^^
SyntaxError: missing ) after argument list
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Function.Module.runMain (module.js:605:10)
    at Object.<anonymous> (C:\Users\Archie\Documents\Coding\Anime-Loader\crawler-v2\node_modules\ts-node\src\_bin.ts:180:12)
    at Module._compile (module.js:571:32)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] ts-node:fast: `ts-node -F "./node_modules/.bin/knex" "migrate:latest"`
npm ERR! Exit status 1

To fix this i had to directly use node_modules/knex/bin/cli.js instead of node_modules/.bin/knex.

After that, when I try to start the app by using npm run serve :

'.' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] serve: `npm run banner serve && ./node_modules/.bin/nodemon --watch 'src/**/*.ts' --watch 'src/**/*.json' --watch '.env'`
npm ERR! Exit status 1

which is triggered by nodemon.
To reproduce run ./node_modules/.bin/nodemon --watch 'src/**/*.ts' in the console.
I have not found a way to fix this.

If i run ./node_modules/.bin/ts-node src/app.ts the app starts normally (with a different error which has nothing to do with windows).

Further, there is an apple-specific script in nodemon.json: "restart": "osascript -e 'display notification \"restarting server\" with title \"node.js application\"'"

Migration and seed when working with mongodb

Hello all,

Please i would like to have some snipets of code that can help me to make migration as well as seeding some user data when working with mongodb.

I commented the call for migration because it gives me some errors when using migration with mongodb

 setup: {
            db: {
                script: series(
                    // 'nps db.migrate',
                    'nps db.seed'
                ),
                description: 'Setup`s the database by migrating and seeding'
            }
        },

and changed the .env file:

DB_TYPE="mongodb"
DB_HOST="localhost"
DB_PORT=27017
DB_DATABASE="mydb"

and changed the seed code like this:

export class CreateBruce implements SeedsInterface {

    public async seed(factory: FactoryInterface): Promise<any> {
        const em = await factory.getConnection().mongoManager;

        const user = new User();
        user.firstName = 'Bruce';
        user.lastName = 'Wayne';
        user.email = '[email protected]';
        return await em.save(user);
    }

}

but when i run :
npm run setup
i get :

executing seed:   CreateBruce
Could not run seed TypeError: this.databaseConnection.collection is not a function
The script called "db.seed" which runs "nps banner.seed && nps config && ts-node -F ./src/lib/seeds/cli.ts" failed with exit code 1 https://github.com/kentcdodds/nps/blob/v5.7.1/other/ERRORS_AND_WARNINGS.md#failed-with-exit-code
The script called "setup.db" which runs "nps db.seed" failed with exit code 1 https://github.com/kentcdodds/nps/blob/v5.7.1/other/ERRORS_AND_WARNINGS.md#failed-with-exit-code
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `nps "setup.db"`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Graphql with dataloader doesn't return the list, only first item

When I change a userId of a pet so that one user will have 2 pets:

id name age user_id
'0e5d9edb-56d4-43df-b96d-b186dcf8a085' 'Darius' '96328' '16919324-89c1-447e-a770-134665993acc'
'21c8cc56-0e71-4ef7-b373-707ec0a7fe97' 'Jadyn' '27435' '16919324-89c1-447e-a770-134665993acc'

export const UserType = new GraphQLObjectType({
    name: 'User',
    description: 'A single user.',
    fields: () => ({ ...UserFields, ...{
        pets: {
            type: new GraphQLList(PetOfUserType),
            description: 'The pets of a user',
            resolve: async (user: User, args: any, context: GraphQLContext<any, any>) =>
                // We use data-loaders to save db queries
                context.dataLoaders.petByUserIds.loadMany([user.id]),
                // This would be the case with a normal service, but not very fast
                // context.container.get<PetService>(PetService).findByUser(user),
        },
    } }),
});

Will return only 1 pet
but:

export const UserType = new GraphQLObjectType({
    name: 'User',
    description: 'A single user.',
    fields: () => ({ ...UserFields, ...{
        pets: {
            type: new GraphQLList(PetOfUserType),
            description: 'The pets of a user',
            resolve: async (user: User, args: any, context: GraphQLContext<any, any>) =>
                // We use data-loaders to save db queries
                // context.dataLoaders.petByUserIds.loadMany([user.id]),
                // This would be the case with a normal service, but not very fast
                context.container.get<PetService>(PetService).findByUser(user),
        },
    } }),
});

Will return 2 pets.

Question about loader

for example i created redisLoader which connects to redis server.
how can i use it in my repository or service?

Thanks in advance

Question: How to assign seeded item to other entity with fix value?

Assume the following entities:

@Entity()
export class TaskType {
    @PrimaryGeneratedColumn() public id: number;
    ...

    @OneToMany(type => Task, task => task.taskType)
    public tasks: Task[];
}
@Entity()
export class Task {
    @PrimaryGeneratedColumn() public id: number;
    
    @IsNotEmpty()
    @Column()
    public name: string;

    @ManyToOne(type => TaskType, taskType => taskType.tasks)
    @JoinTable()
    public taskType: TaskType;
}

A task can have one of the two following types: 'simple' or 'qualityCheck'. Seeding tasks and taskTypes separately works fine but not with the relation. I tried it with nested factories as described in the docs, this although works only with dynamic values, right?

A Task belongs to a DataCenter - following seed:

await times(10, async (n) => {
    const dc = await factory.get(DataCenter).create();
    dc.tasks = await factory.get(Task).createMany(5);
    dc.areas = await factory.get(Area).createMany(randomNumber(5, 10));
    await em.save(dc);
});

Can't setup on windows

On windows I'm getting and error when running npm run setup:

C:\Users\Vincas\Desktop\express-typescript-boilerplate\node_modules\.bin\knex:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
          ^^^^^^^
SyntaxError: missing ) after argument list
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Function.Module.runMain (module.js:604:10)
    at Object.<anonymous> (C:\Users\Vincas\Desktop\express-typescript-boilerplate\node_modules\ts-node\src\_bin.ts:180:12)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)

Looks like it is trying to execute .sh script on windows and can't make out the syntax

How do you manage multiple environments?

For example, say production has a different database name than development. How would you manage this? Two thoughts come to mind:

Either make .env.development and .env.production and copy the the correct .env file over. Or set environment variables in the production environment that sets DB_NAME. However, isn't great since you can't have that in version control.
A third option is to completely drop the custom environment handling and use something like convict.

No more scaffolding?

Hi,

I just checkout this boilerplate, but npm run console is now not available? did you make separate project for that or it is gone for good?

Best Regards,
Jason Villalon

Server doesn't run after cloning

When i try to run the project (compiled by using npm run build) with npm run start i get the following error:

> node dist/app.js

info: [C:\path\to\app\dist\core\App.js] Defining app...
info: [C:\path\to\app\dist\core\App.js] Configuring app...
debug: [C:\path\to\app\dist\config\CustomConfig.js] configuring 0=[3000]
info: [C:\path\to\app\dist\core\App.js] Binding IoC modules...
info: [C:\path\to\app\dist\core\App.js] Setting up IoC...
error: [C:\path\to\app\dist\core\Bootstrap.js] No matching bindings found for serviceIdentifier: Symbol(Controller)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `node dist/app.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Archie\AppData\Roaming\npm-cache\_logs\2017-07-10T18_20_34_969Z-debug.log

Any pointers to how I can fix this?

Serving public doesn't work when in prod

I can serve the frontend from the public folder when running npm start serve. I doesn't work though when running it from the prod build/npm start.

Is there any additional config to be done?

Can't run npm start setup

I'm on Lubuntu 17.04 running on an virtualbox latest release. Following your readme, I first created a new database on the local mysql server and entered its name and the credentials in .env. When issuing 'npm start setup' I get the following error messages (this is the content of the generated logfile):
0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'start', 'setup' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle [email protected]prestart: [email protected]
6 info lifecycle [email protected]
start: [email protected]
7 verbose lifecycle [email protected]start: unsafe-perm in lifecycle true
8 verbose lifecycle [email protected]
start: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/nn/Projects/Examples/express-typescript-boilerplate/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin
9 verbose lifecycle [email protected]start: CWD: /home/nn/Projects/Examples/express-typescript-boilerplate
10 silly lifecycle [email protected]
start: Args: [ '-c', 'nps "setup"' ]
11 silly lifecycle [email protected]start: Returned: code: 1 signal: null
12 info lifecycle [email protected]
start: Failed to exec start script
13 verbose stack Error: [email protected] start: nps "setup"
13 verbose stack Exit status 1
13 verbose stack at EventEmitter. (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:285:16)
13 verbose stack at emitTwo (events.js:126:13)
13 verbose stack at EventEmitter.emit (events.js:214:7)
13 verbose stack at ChildProcess. (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack at emitTwo (events.js:126:13)
13 verbose stack at ChildProcess.emit (events.js:214:7)
13 verbose stack at maybeClose (internal/child_process.js:925:16)
13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
14 verbose pkgid [email protected]
15 verbose cwd /home/nn/Projects/Examples/express-typescript-boilerplate
16 verbose Linux 4.10.0-42-generic
17 verbose argv "/usr/bin/node" "/usr/bin/npm" "start" "setup"
18 verbose node v8.9.3
19 verbose npm v5.6.0
20 error code ELIFECYCLE
21 error errno 1
22 error [email protected] start: nps "setup"
22 error Exit status 1
23 error Failed at the [email protected] start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

Question: What did I overlook? What would I have to do differently?

Cheers, Wolfram

'.' is not recognized as an internal or external command

Hi,
with version 2.0.0-beta.4, branch develop, I have this error on Win 10 64bit, node v8.8.1, nps 5.7.1:

D:\_note_in_cloud_be\express-typescript-boilerplate>nps build
nps is executing `build` : nps banner.build && nps lint && nps clean.dist && nps transpile && nps copy
nps is executing `banner.build` : ./node_modules/.bin/ts-node -F ./src/console/lib/banner.ts build
'.' is not recognized as an internal or external command,
operable program or batch file.
The script called "banner.build" which runs "./node_modules/.bin/ts-node -F ./src/console/lib/banner.ts build" failed with exit code 1 https://github.com/kentcdodds/nps/blob/v5.7.1/other/ERRORS_AND_WARNINGS.md#failed-with-exi
t-code
The script called "build" which runs "nps banner.build && nps lint && nps clean.dist && nps transpile && nps copy" failed with exit code 1 https://github.com/kentcdodds/nps/blob/v5.7.1/other/ERRORS_AND_WARNINGS.md#failed-with
-exit-code

Any suggest? The problem occurs with any command (aka nps db.reset)

Thank's
Claudio

The engine "node" is incompatible with this module. Expected version "^7.7.3.

Thanks for a super nice and thorough boilerplate, loving the file structure you use! :)

Any reason why you have "engine": {"node": "^7.7.3"} in package.json? It breaks npm run setup when using Node.js v8.5. I removed that line from package.json and then the setup is working. So seems like an unnecessary "safety" check to lock down the node version, no?

This is the error I got while keeping those lines in package.json if anyone searches for this.

npm run setup
...
error [email protected]: The engine "node" is incompatible with this module. Expected version "^7.7.3".
...

errors launch with last commit

Hello,

When I do the npm run setup, I have :

yarn install v1.3.2
[1/5] 🔍  Validating package.json...
[2/5] 🔍  Resolving packages...
[3/5] 🚚  Fetching packages...
[4/5] 🔗  Linking dependencies...
[5/5] 📃  Building fresh packages...
success Saved lockfile.
✨  Done in 2.98s.

> [email protected] setup /Users/far-paul/Sites/printaplus/express-typescript-boilerplate
> npm start setup.db


> [email protected] start /Users/far-paul/Sites/printaplus/express-typescript-boilerplate
> nps "setup.db"

Scripts must resolve to strings. There is no script that can be resolved from "setup.db" https://github.com/kentcdodds/nps/blob/v5.7.1/other/ERRORS_AND_WARNINGS.md#missing-script
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `nps "setup.db"`
npm ERR! Exit status 1

Thanks

Log.ts : duplicated methods with different modifiers.

Hi,
This is a very nice and clean boilerplate !! even if I'm new to typescript, it feels solid enough to build on top of it, but I have question about the reason of the duplication of methods (debug, info, warn, error, log) in src/core/log/Log.ts while setting different modifiers for them.

Socket IO Integration

Hi,

Ive been using this boilerplate for a while. now im integrating socket.io but noticed weird behavior. i tried to remove my integration and looks like the server still accepts socket connection. is there a ready socket integration in this boilerplate? im keep on digging but cant find anything which is weird.

Best Regards,
Jason Villalon

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.