commands:
  yarn_install:
    description: "A wrapper to yarn install with caching"
    parameters:
      working_directory:
        type: string
        default: ""
    steps:
      - restore_cache:
          keys:
            - dependencies-{{ .Branch }}-{{ checksum "yarn.lock" }}
            # Fallback in case checksum fails
            - dependencies-{{ .Branch }}-
      - run:
          command: NPM_TOKEN= yarn --no-progress
          working_directory: << parameters.working_directory >>
      - save_cache:
          paths:
            - node_modules
          key: dependencies-{{ .Branch }}-{{ checksum "yarn.lock" }}

  yarn_run:
    description: "A wrapper to execute yarn commands in a safe way"
    parameters:
      working_directory:
        type: string
        default: ""
      command:
        type: string
    steps:
      - run:
          command: NPM_TOKEN= yarn run << parameters.command >>
          working_directory: << parameters.working_directory >>

version: 2.1
jobs:
  run-js-checks:
    docker:
      - image: circleci/node:12
    steps:
      - checkout
      - yarn_install
      - yarn_run:
          command: test-ci

  test-node-12:
    docker:
      - image: circleci/node:12
    steps:
      - checkout
      - yarn_install
      - yarn_run:
          command: jest -w 4

  publish-to-npm:
    docker:
      - image: circleci/node:12
    steps:
      - checkout
      - yarn_install
      - run: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc
      - run: npm run publish
      - run: rm ~/.npmrc

# Workflows enables us to run multiple jobs in parallel
workflows:
  version: 2
  build-and-deploy:
    jobs:
      - run-js-checks
      - test-node-12
      - publish-to-npm:
          filters:
            branches:
              ignore: /.*/
            tags:
              only: /v[0-9]+(\.[0-9]+)*/
