version: 2

defaults: &defaults
  working_directory: ~/repo
  docker:
    - image: circleci/node:8.9.1

jobs:
  build:
    <<: *defaults
    steps:
      - checkout
      - restore_cache:
          key: npm-cache-v1-{{ checksum "package-lock.json" }}
      - run:
          name: Install Dependencies
          command: npm i
      - save_cache:
          key: npm-cache-v1-{{ checksum "package-lock.json" }}
          paths:
            - /home/circleci/.npm      
  test:
    <<: *defaults
    steps:
      - checkout
      - restore_cache:
          key: npm-cache-v1-{{ checksum "package-lock.json" }}
      - run:
          name: Install Dependencies
          command: npm i
      - save_cache:
          key: npm-cache-v1-{{ checksum "package-lock.json" }}
          paths:
            - /home/circleci/.npm      
      - run:
          name: Run Tests
          command: npm test
  deploy:
    <<: *defaults
    steps:      
      - checkout
      - restore_cache:
          key: npm-cache-v1-{{ checksum "package-lock.json" }}
      - run:
          name: Install Dependencies
          command: npm i
      - save_cache:
          key: npm-cache-v1-{{ checksum "package-lock.json" }}
          paths:
            - /home/circleci/.npm      
      - run:
          name: "Build project"
          command: npm run build
      - run:
          name: Authenticate with registry
          command: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > ~/repo/.npmrc
      - run:
          name: Publish package
          command: npm publish

workflows:
  version: 2
  test-deploy:
    jobs:
      - build
      - test:
          requires:
            - build
      - deploy:
          requires:
            - test
          filters:
            branches:
              only:
                - master
