Skip to content

Commit

Permalink
feat: getCurrentLocationWithTimeout
Browse files Browse the repository at this point in the history
BREAKING CHANGE: First Release
  • Loading branch information
ReiiYuki committed Mar 30, 2023
1 parent 8ac8ea9 commit 6c34fbe
Show file tree
Hide file tree
Showing 19 changed files with 6,721 additions and 1 deletion.
7 changes: 7 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": ["standard"],
"rules": {
"no-console": "off",
"semi": ["error", "never"]
}
}
28 changes: 28 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: Release
on:
push:
branches:
- main

jobs:
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: 'lts/*'
- name: Install dependencies
run: yarn
- name: Build
run: yarn build
- name: Release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npx semantic-release
15 changes: 15 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
logs
*.log
npm-debug.log*
.DS_Store

coverage
node_modules
build
.env.local
.env.development.local
.env.test.local
.env.production.local

*.cache
.env
5 changes: 5 additions & 0 deletions .huskyrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"hooks": {
"pre-commit": "lint-staged"
}
}
4 changes: 4 additions & 0 deletions .lintstagedrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"*.{ts,js}": ["prettier --write", "eslint --fix", "git add"],
"*.svg": ["svgo", "git add"]
}
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
lts/fermium
11 changes: 11 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"bracketSpacing": true,
"jsxBracketSameLine": false,
"printWidth": 100,
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "all",
"useTabs": true,
"arrowParens": "avoid"
}
3 changes: 3 additions & 0 deletions .releaserc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"branches": ["main"]
}
1 change: 1 addition & 0 deletions .yarnrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
save-prefix ""
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2023 Wongnai
Copyright (c) 2023 LINE MAN Wongnai

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Get Location With Timeout

[![semantic-release](https://img.shields.io/badge/semantic-release-e10079.svg?logo=semantic-release)](https://github.com/semantic-release/semantic-release)
[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)
![ts](https://badgen.net/badge/Built%20With/TypeScript/blue) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Wrapper for navigator.geolocation.getCurrentPosition with ensure rejected the promise when timeout

## Installation

```
yarn add get-location-with-timeout
```

### Usage

```ts
import getCurrentLocationWithTimeout, { TiredFromWaitingPromiseResolveTooLongError } from 'get-location-with-timeout'

try {
const { coords } = await getCurrentLocationWithTimeout()

// logic
} catch (error) {
if (error instanceof TimeoutError) {
// handle timeout logic
} else {
// handle other reject logic
}
}
```
27 changes: 27 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
module.exports = {
moduleFileExtensions: ['json', 'ts', 'js'],
transform: {
'^.+\\.ts$': 'ts-jest',
},
testRegex: '((\\.|/)(test|spec))\\.ts$',
transformIgnorePatterns: ['/node_modules/', '/dist/'],
testEnvironment: 'jsdom',
moduleDirectories: ['node_modules', 'src'],
coverageReporters: ['cobertura', 'lcov', 'json', 'text'],
coverageThreshold: {
global: {
statements: 80,
branches: 80,
functions: 80,
lines: 80,
},
},
collectCoverageFrom: [
'src/**/*.ts',
'!src/**/*.d.ts',
'!src/**/types.ts',
'!src/**/constants.ts',
'!src/types/index.ts',
],
testTimeout: 50000,
}
44 changes: 44 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
{
"name": "get-location-with-timeout",
"version": "0.0.0",
"types": "build",
"deploy": "build",
"entry": "src/index.ts",
"main": "build/index.js",
"repository": {
"type": "git",
"url": "https://github.com/wongnai/get-location-with-timeout.git"
},
"homepage": "https://github.com/wongnai/get-location-with-timeout#readme",
"license": "MIT",
"scripts": {
"build": "rollup -c",
"lint": "eslint --ext .ts,.js --quiet",
"test": "jest --coverage"
},
"devDependencies": {
"@rollup/plugin-commonjs": "19.0.0",
"@rollup/plugin-json": "4.1.0",
"@rollup/plugin-node-resolve": "13.0.0",
"@rollup/plugin-typescript": "8.2.1",
"@types/jest": "27.0.2",
"@types/node": "15.12.1",
"@types/qs": "6.9.7",
"eslint": "7.28.0",
"eslint-config-standard": "16.0.3",
"husky": "6.0.0",
"jest": "27.3.1",
"lint-staged": "11.0.0",
"prettier": "2.3.1",
"rollup": "2.51.0",
"rollup-plugin-cleaner": "1.0.0",
"rollup-plugin-includepaths": "0.2.4",
"rollup-plugin-visualizer": "5.5.0",
"semantic-release": "21.0.0",
"ts-jest": "27.0.7",
"typescript": "4.4.4"
},
"dependencies": {
"promise-until-tired": "1.0.1"
}
}
33 changes: 33 additions & 0 deletions rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import path from 'path'

import commonjs from '@rollup/plugin-commonjs'
import json from '@rollup/plugin-json'
import resolve from '@rollup/plugin-node-resolve'
import typescript from '@rollup/plugin-typescript'
import visualizer from 'rollup-plugin-visualizer'

import config from './package.json'

export default [{
input: config.entry,
output: {
format: 'cjs',
sourcemap: true,
dir: config.deploy,
},
plugins: [
resolve({
browser: true,
}),
commonjs(),
typescript({
declaration: true,
declarationDir: config.deploy,
exclude: 'src/**/*.test.ts',
}),
json(),
visualizer({
filename: path.resolve(config.deploy, 'stat.html'),
}),
],
}]
101 changes: 101 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import getCurrentLocationWithTimeout from "index"
import { TiredFromWaitingPromiseResolveTooLongError } from "promise-until-tired"

describe('getCurrentLocationWithTimeout()', () => {
const MOCK_RESPONSE = {
coords: {
latitude: 51.1,
longitude: 45.3
}
}

const MOCK_REJECT_RESPONSE = new Error('reject')

const mockGetCurrentPosition = jest.fn()

beforeAll(() => {
Object.defineProperty(window, 'navigator', {
value: {
geolocation: {
getCurrentPosition: mockGetCurrentPosition,
},
},
})
})

afterEach(() => {
mockGetCurrentPosition.mockClear()
})

describe('geolocation resolve after timeout', () => {
beforeEach(() => {
mockGetCurrentPosition.mockImplementation(resolve => {
setTimeout(() => {
resolve(MOCK_RESPONSE)
}, 50000)
})
})

it('should reject with timeout error (with default timeout)', async () => {
await expect(getCurrentLocationWithTimeout()).rejects.toBeInstanceOf(TiredFromWaitingPromiseResolveTooLongError)
})

it('should reject with timeout error (with input timeout)', async () => {
await expect(getCurrentLocationWithTimeout({ timeout: 1000 })).rejects.toBeInstanceOf(TiredFromWaitingPromiseResolveTooLongError)
})
})

describe('geolocation reject after timeout', () => {
beforeEach(() => {
mockGetCurrentPosition.mockImplementation((_, reject) => {
setTimeout(() => {
reject(MOCK_REJECT_RESPONSE)
}, 50000)
})
})

it('should reject with timeout error (with default timeout)', async () => {
await expect(getCurrentLocationWithTimeout()).rejects.toBeInstanceOf(TiredFromWaitingPromiseResolveTooLongError)
})

it('should reject with timeout error (with input timeout)', async () => {
await expect(getCurrentLocationWithTimeout({ timeout: 1000 })).rejects.toBeInstanceOf(TiredFromWaitingPromiseResolveTooLongError)
})
})

describe('geolocation resolve before timeout', () => {
beforeEach(() => {
mockGetCurrentPosition.mockImplementation(resolve => {
setTimeout(() => {
resolve(MOCK_RESPONSE)
}, 500)
})
})

it('should reject with timeout error (with default timeout)', async () => {
await expect(getCurrentLocationWithTimeout()).resolves.toEqual(MOCK_RESPONSE)
})

it('should reject with timeout error (with input timeout)', async () => {
await expect(getCurrentLocationWithTimeout({ timeout: 1000 })).resolves.toEqual(MOCK_RESPONSE)
})
})

describe('geolocation reject before timeout', () => {
beforeEach(() => {
mockGetCurrentPosition.mockImplementation((_, reject) => {
setTimeout(() => {
reject(MOCK_REJECT_RESPONSE)
}, 500)
})
})

it('should reject with timeout error (with default timeout)', async () => {
await expect(getCurrentLocationWithTimeout()).rejects.toEqual(MOCK_REJECT_RESPONSE)
})

it('should reject with timeout error (with input timeout)', async () => {
await expect(getCurrentLocationWithTimeout({ timeout: 1000 })).rejects.toEqual(MOCK_REJECT_RESPONSE)
})
})
})
12 changes: 12 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import newPromiseUntilTired, { TiredFromWaitingPromiseResolveTooLongError } from 'promise-until-tired'
import { DEFAULT_TIMEOUT } from './variables'

function getCurrentLocationWithTimeout(options?: PositionOptions) {
return newPromiseUntilTired<GeolocationPosition>((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject, options)
}, options?.timeout || DEFAULT_TIMEOUT)
}

export const TimeoutError = TiredFromWaitingPromiseResolveTooLongError

export default getCurrentLocationWithTimeout
1 change: 1 addition & 0 deletions src/variables.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const DEFAULT_TIMEOUT = 30000
29 changes: 29 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"compilerOptions": {
"target": "es2019",
"module": "esnext",
"strict": true,
"baseUrl": "./src",
"importHelpers": true,
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"types": [
"jest",
"node"
],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": false,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true
},
"include": [
"src/**/*.ts",
],
"exclude": [
"node_modules"
]
}
Loading

0 comments on commit 6c34fbe

Please sign in to comment.