version: 2

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

jobs:
  test:
    <<: *defaults
    steps:
      - checkout

      - restore_cache:
          keys:
            - v1-dependencies-{{ checksum "package.json" }}
            - v1-dependencies-

      - run:
          name: Install dependancies
          command: npm install

      - save_cache:
          paths:
            - node_modules
          key: v1-dependencies-{{ checksum "package.json" }}

      - persist_to_workspace:
          root: ~/repo
          paths: .

  deploy_beta:
    <<: *defaults
    steps:
      - attach_workspace:
          at: ~/repo
      - run:
          name: Authenticate with NPM
          command: echo "//registry.npmjs.org/:_authToken=$npm_TOKEN" > ~/repo/.npmrc
      - run:
          name: Publish beta package
          command: npm publish --tag beta --access public

  deploy:
    <<: *defaults
    steps:
      - attach_workspace:
          at: ~/repo
      - run:
          name: Authenticate with NPM
          command: echo "//registry.npmjs.org/:_authToken=$npm_TOKEN" > ~/repo/.npmrc
      - run:
          name: Publish package
          command: npm publish --access public

workflows:
  version: 2
  test-deploy-beta:
    jobs:
      - test:
          filters:
            tags:
              only: /.*/
      - deploy_beta:
          requires:
            - test
          filters:
            tags:
              only: /^.*-preview/
            branches:
              ignore: master
      - deploy:
          requires:
            - test
          filters:
            tags:
              only: /^.*/
            branches:
              only: master