1
0
mirror of https://github.com/uetchy/namae.git synced 2025-08-20 01:48:12 +09:00

feat(api): typescript

This commit is contained in:
2019-08-30 16:40:22 +09:00
parent 6fbd0346d0
commit f2e45bac4b
24 changed files with 340 additions and 878 deletions

1
.gitignore vendored
View File

@@ -1,4 +1,5 @@
.vscode
/api/dist
/web/build
# Created by https://www.gitignore.io/api/node

View File

@@ -1,10 +0,0 @@
{
"presets": [
[
"@babel/preset-env",
{
"targets": { "node": "current" }
}
]
]
}

View File

@@ -1,4 +1,7 @@
module.exports = {
automock: false,
setupFiles: ['./setupJest.js'],
setupFiles: ['./setupJest.ts'],
testEnvironment: 'node',
preset: 'ts-jest',
testPathIgnorePatterns: ['/dist/'],
}

View File

View File

@@ -2,20 +2,26 @@
"name": "@namae/api",
"version": "0.1.0",
"scripts": {
"build": "tsc",
"now-build": "tsc",
"start": "tsc -w",
"test": "jest"
},
"dependencies": {
"google-it": "^1.2.1",
"isomorphic-unfetch": "^3.0.0",
"npm-name": "^5.5.0",
"typescript": "^3.6.2",
"whois-json": "^2.0.4"
},
"devDependencies": {
"@babel/preset-env": "^7.5.5",
"@types/jest": "^24.0.18",
"babel-jest": "^24.9.0",
"@types/nock": "^10.0.3",
"@types/node": "^12.7.3",
"@types/node-fetch": "^2.5.0",
"jest": "^24.9.0",
"nock": "^10.0.6"
"nock": "^10.0.6",
"ts-jest": "^24.0.2"
},
"private": true
}

View File

@@ -1,6 +1,22 @@
const { send, sendError, fetch } = require('../util/http')
import { send, sendError, fetch, NowRequest, NowResponse } from '../util/http'
module.exports = async (req, res) => {
interface App {
trackId: string
trackName: string
kind: string
version: string
price: string
trackViewUrl: string
}
interface AppStoreResponse {
results: App[]
}
export default async function handler(
req: NowRequest<{ query: string; country: string }>,
res: NowResponse
) {
const { query, country } = req.query
if (!query) {
@@ -16,7 +32,7 @@ module.exports = async (req, res) => {
`https://itunes.apple.com/search?media=software&entity=software,iPadSoftware,macSoftware&country=${countryCode}&limit=${limit}&term=${term}`,
'GET'
)
const body = await response.json()
const body: AppStoreResponse = await response.json()
const apps = body.results.map((app) => ({
id: app.trackId,
name: app.trackName,

View File

@@ -1,6 +1,6 @@
const { send, sendError, fetch } = require('../util/http')
import { send, sendError, fetch, NowRequest, NowResponse } from '../util/http'
module.exports = async (req, res) => {
export default async function handler(req: NowRequest, res: NowResponse) {
const { query } = req.query
if (!query) {

View File

@@ -1,7 +1,7 @@
var dns = require('dns')
const { send, sendError } = require('../util/http')
import dns from 'dns'
import { send, sendError, NowRequest, NowResponse } from '../util/http'
function resolvePromise(hostname) {
function resolvePromise(hostname: string): Promise<string[]> {
return new Promise((resolve, reject) => {
dns.resolve4(hostname, function(err, addresses) {
if (err) return reject(err)
@@ -10,7 +10,7 @@ function resolvePromise(hostname) {
})
}
module.exports = async (req, res) => {
export default async function handler(req: NowRequest, res: NowResponse) {
const { query } = req.query
if (!query) {

View File

@@ -1,7 +1,7 @@
import whois from 'whois-json'
const { send, sendError } = require('../util/http')
import { send, sendError, NowRequest, NowResponse } from '../util/http'
module.exports = async (req, res) => {
export default async function handler(req: NowRequest, res: NowResponse) {
const { query } = req.query
if (!query) {

View File

@@ -1,6 +1,6 @@
const { send, sendError, fetch } = require('../util/http')
import { send, sendError, fetch, NowRequest, NowResponse } from '../util/http'
module.exports = async (req, res) => {
export default async function handler(req: NowRequest, res: NowResponse) {
const { query } = req.query
if (!query) {

View File

@@ -1,5 +1,7 @@
import provider from './existence'
import nock from 'nock'
import { mockProvider } from '../util/testHelpers'
import provider from './existence'
test('return false if name is taken', async () => {
const result = await mockProvider(provider, { query: 'github.com/uetchy' })
@@ -16,104 +18,64 @@ test('return true if name is not taken', async () => {
beforeEach(() => {
nock('https://github.com:443', { encodedQueryParams: true })
.head('/uetchyasdf')
.reply(
404,
[],
[
'Date',
'Wed, 14 Aug 2019 10:52:54 GMT',
'Content-Type',
'text/plain; charset=utf-8',
'Connection',
'close',
'Server',
'GitHub.com',
'Status',
'404 Not Found',
'Vary',
'X-PJAX',
'Cache-Control',
'no-cache',
'Set-Cookie',
.reply(404, [], {
Date: 'Wed, 14 Aug 2019 10:52:54 GMT',
'Content-Type': 'text/plain; charset=utf-8',
Connection: 'close',
Server: 'GitHub.com',
Status: '404 Not Found',
Vary: 'X-PJAX',
'Cache-Control': 'no-cache',
'Set-Cookie': [
'has_recent_activity=1; path=/; expires=Wed, 14 Aug 2019 11:52:54 -0000',
'Set-Cookie',
'logged_in=no; domain=.github.com; path=/; expires=Sun, 14 Aug 2039 10:52:54 -0000; secure; HttpOnly',
'Set-Cookie',
'_gh_sess=L0ZETUlMOEYxa3R3ZHRmMXlwYlRDQ1htRXZDMXA0WTJaMm5FTmJ6WnNjL0wrRERtbVRnck10Q3R6ZHpoV1JEaWoyQ3RNSFdXSW9KWFAycy9JZnJUY0RRbXlsSGpHREdPTmluTDA3S1JmamVIUXI0U29xVnhUNkRZZEVZNEdnSm8tLWIyZTA4OU12MHVhblhzSmIvYzFFdWc9PQ%3D%3D--2c1699922db712db405ce841c8863aaccd1dc293; path=/; secure; HttpOnly',
'X-Request-Id',
'c9060424-821a-4a42-aacb-f8325f946d3a',
'Strict-Transport-Security',
'_gh_sess=L0ZETUlMOEYxa3R3ZHRmMXlwYlRDQ1htRXZDMXA0WTJaMm5FTmJ6WnNjL0wrRERtbVRnck10Q3R6ZHpoV1JEaWoyQ3RNSFdXSW9KWFAycy,JZnJUY0RRbXlsSGpHREdPTmluTDA3S1JmamVIUXI0U29xVnhUNkRZZEVZNEdnSm8tLWIyZTA4OU12MHVhblhzSmIvYzFFdWc9PQ%3D%3D--2c1699922db712db405ce841c8863aaccd1dc293; path=/; secure; HttpOnly',
],
'X-Request-Id': 'c9060424-821a-4a42-aacb-f8325f946d3a',
'Strict-Transport-Security':
'max-age=31536000; includeSubdomains; preload',
'X-Frame-Options',
'deny',
'X-Content-Type-Options',
'nosniff',
'X-XSS-Protection',
'1; mode=block',
'Referrer-Policy',
'X-Frame-Options': 'deny',
'X-Content-Type-Options': 'nosniff',
'X-XSS-Protection': '1; mode=block',
'Referrer-Policy':
'origin-when-cross-origin, strict-origin-when-cross-origin',
'Expect-CT',
'Expect-CT':
'max-age=2592000, report-uri="https://api.github.com/_private/browser/errors"',
'Content-Security-Policy',
"default-src 'none'; base-uri 'self'; connect-src 'self'; form-action 'self'; img-src 'self' data:; script-src 'self'; style-src 'unsafe-inline'",
'Content-Encoding',
'gzip',
'X-GitHub-Request-Id',
'BA06:51D6:125A0F:1A9B4A:5D53E806',
]
)
'Content-Security-Policy':
"default-src 'none'; base-uri 'self'; connect-src 'self'; form-action 'self'; img-src 'self' data:; script-src,'self'; style-src 'unsafe-inline'",
'Content-Encoding': 'gzip',
'X-GitHub-Request-Id': 'BA06:51D6:125A0F:1A9B4A:5D53E806',
})
nock('https://github.com:443', { encodedQueryParams: true })
.head('/uetchy')
.reply(
200,
[],
[
'Date',
'Wed, 14 Aug 2019 10:43:09 GMT',
'Content-Type',
'text/html; charset=utf-8',
'Connection',
'close',
'Server',
'GitHub.com',
'Status',
'200 OK',
'Vary',
'X-Requested-With',
'ETag',
'W/"1d0b1abdacee756e874ad8ecbc350aea"',
'Cache-Control',
'max-age=0, private, must-revalidate',
'Set-Cookie',
.reply(200, [], {
Date: 'Wed, 14 Aug 2019 10:43:09 GMT',
'Content-Type': 'text/html; charset=utf-8',
Connection: 'close',
Server: 'GitHub.com',
Status: '200 OK',
Vary: ['X-Requested-With', 'Accept-Encoding'],
ETag: 'W/"1d0b1abdacee756e874ad8ecbc350aea"',
'Cache-Control': 'max-age=0, private, must-revalidate',
'Set-Cookie': [
'has_recent_activity=1; path=/; expires=Wed, 14 Aug 2019 11:43:08 -0000',
'Set-Cookie',
'_octo=GH1.1.1968814248.1565779389; domain=.github.com; path=/; expires=Sat, 14 Aug 2021 10:43:09 -0000',
'Set-Cookie',
'logged_in=no; domain=.github.com; path=/; expires=Sun, 14 Aug 2039 10:43:09 -0000; secure; HttpOnly',
'Set-Cookie',
'_gh_sess=VFVEY3RvRkp6UGlHZnAxM1JET3lGV1dDU2lzbTltcDZGNlVaWUp4cGx2WERIaDhvU3QydU83UUU3WkdzSHVCRGZSZUhrNG85Q2llRVA4TUg0Q1BRYUVhRVhIUHozSGJ2cDVab1J5SkE0dW9tVU04TW96bVRJcWpXSU0ydmQ0V1FiNy9tVitBQTdYS0tvR3UzVjdpTXd1MHJJeSt3OTB5RkFJUlpxSm1rT0VFRDNIb2RGeEhvWHhaUzlOc1JEdlZkTTJRQnNOamZaSEVMWHBacVkrdys3Zz09LS1tT05yQUpQUWdrR2hvKzhkK2U1WGFRPT0%3D--fa39d5bf1e2d5a9bc9fcf927fce211a2a0cf07bb; path=/; secure; HttpOnly',
'X-Request-Id',
'38b2d3b9-21df-49d4-9cf5-8b85181fa67e',
'Strict-Transport-Security',
],
'X-Request-Id': '38b2d3b9-21df-49d4-9cf5-8b85181fa67e',
'Strict-Transport-Security':
'max-age=31536000; includeSubdomains; preload',
'X-Frame-Options',
'deny',
'X-Content-Type-Options',
'nosniff',
'X-XSS-Protection',
'1; mode=block',
'Referrer-Policy',
'X-Frame-Options': 'deny',
'X-Content-Type-Options': 'nosniff',
'X-XSS-Protection': '1; mode=block',
'Referrer-Policy':
'origin-when-cross-origin, strict-origin-when-cross-origin',
'Expect-CT',
'Expect-CT':
'max-age=2592000, report-uri="https://api.github.com/_private/browser/errors"',
'Content-Security-Policy',
'Content-Security-Policy':
"default-src 'none'; base-uri 'self'; block-all-mixed-content; connect-src 'self' uploads.github.com www.githubstatus.com collector.githubapp.com api.github.com www.google-analytics.com github-cloud.s3.amazonaws.com github-production-repository-file-5c1aeb.s3.amazonaws.com github-production-upload-manifest-file-7fdce7.s3.amazonaws.com github-production-user-asset-6210df.s3.amazonaws.com wss://live.github.com; font-src github.githubassets.com; form-action 'self' github.com gist.github.com; frame-ancestors 'none'; frame-src render.githubusercontent.com; img-src 'self' data: github.githubassets.com identicons.github.com collector.githubapp.com github-cloud.s3.amazonaws.com *.githubusercontent.com; manifest-src 'self'; media-src 'none'; script-src github.githubassets.com; style-src 'unsafe-inline' github.githubassets.com",
'Content-Encoding',
'gzip',
'Vary',
'Accept-Encoding',
'X-GitHub-Request-Id',
'A922:19B1:AD411:FB69F:5D53E5BC',
]
)
'Content-Encoding': 'gzip',
'X-GitHub-Request-Id': 'A922:19B1:AD411:FB69F:5D53E5BC',
})
})

View File

@@ -1,6 +1,6 @@
const { send, sendError, fetch } = require('../util/http')
import { send, sendError, fetch, NowRequest, NowResponse } from '../util/http'
module.exports = async (req, res) => {
export default async function handler(req: NowRequest, res: NowResponse) {
const { query } = req.query
if (!query) {

View File

@@ -1,7 +1,7 @@
const npmName = require('npm-name')
const { send, sendError } = require('../util/http')
import npmName from 'npm-name'
import { send, sendError, fetch, NowRequest, NowResponse } from '../util/http'
module.exports = async (req, res) => {
export default async function handler(req: NowRequest, res: NowResponse) {
const { query } = req.query
if (!query) {

View File

@@ -1,7 +1,7 @@
const npmName = require('npm-name')
const { send, sendError } = require('../util/http')
import npmName from 'npm-name'
import { send, sendError, NowRequest, NowResponse } from '../util/http'
module.exports = async (req, res) => {
export default async function handler(req: NowRequest, res: NowResponse) {
const { query } = req.query
if (!query) {

View File

@@ -1,6 +1,6 @@
const { send, sendError, fetch } = require('../util/http')
import { send, sendError, fetch, NowRequest, NowResponse } from '../util/http'
module.exports = async (req, res) => {
export default async function handler(req: NowRequest, res: NowResponse) {
const { query } = req.query
if (!query) {
@@ -15,7 +15,7 @@ module.exports = async (req, res) => {
send(res, { availability })
} catch (err) {
if (err.code === 'ENOTFOUND') {
send(res, true)
send(res, { availability: true })
} else {
sendError(res, err)
}

View File

@@ -1,6 +1,6 @@
const { send, sendError, fetch } = require('../util/http')
import { send, sendError, fetch, NowResponse, NowRequest } from '../util/http'
module.exports = async (req, res) => {
export default async function handler(req: NowRequest, res: NowResponse) {
const { query } = req.query
if (!query) {

5
api/setupJest.ts Normal file
View File

@@ -0,0 +1,5 @@
import nock from 'nock'
nock.disableNetConnect()
// nock.recorder.rec()

63
api/tsconfig.json Normal file
View File

@@ -0,0 +1,63 @@
{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
// "lib": [], /* Specify library files to be included in the compilation. */
"allowJs": true /* Allow javascript files to be compiled. */,
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist" /* Redirect output structure to the directory. */,
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}

1
api/types/whois-json.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
declare module 'whois-json'

View File

@@ -1,14 +0,0 @@
const fetch = require('isomorphic-unfetch')
exports.fetch = (url, method = 'HEAD') => {
return fetch(url, { method })
}
exports.send = (res, data) => {
res.setHeader('Cache-Control', 'maxage=0, s-maxage=43200')
res.json(data)
}
exports.sendError = (res, error) => {
res.status(400).json({ error: error.message })
}

35
api/util/http.ts Normal file
View File

@@ -0,0 +1,35 @@
import nodeFetch from 'isomorphic-unfetch'
export type HttpMethod =
| 'GET'
| 'POST'
| 'PUT'
| 'DELETE'
| 'HEAD'
| 'PATCH'
| 'CONNECT'
| 'TRACE'
export interface NowRequest<T = { query: string }> {
query: T
}
export interface NowResponse {
setHeader: (label: string, body: string) => void
json: (obj: object) => void
status: (code: number) => NowResponse
length: number
}
export function fetch(url: string, method: HttpMethod = 'HEAD') {
return nodeFetch(url, { method: method })
}
export function send(res: NowResponse, data: object) {
res.setHeader('Cache-Control', 'maxage=0, s-maxage=43200')
res.json(data)
}
export function sendError(res: NowResponse, error: Error) {
res.status(400).json({ error: error.message })
}

View File

@@ -1,10 +1,4 @@
import nock from 'nock'
nock.disableNetConnect()
// nock.recorder.rec()
global.mockProvider = async (provider, query) => {
export async function mockProvider(provider: any, query: any) {
const req = {
query,
}

File diff suppressed because it is too large Load Diff

View File

@@ -9,14 +9,14 @@
"config": { "distDir": "build" }
},
{
"src": "/api/services/*.js",
"use": "@now/node"
"src": "/api/services/*.ts",
"use": "@now/node@canary"
}
],
"routes": [
{
"src": "/availability/(?<provider>[^/]+)/(?<query>[^/]+)",
"dest": "/api/services/$provider.js?query=$query"
"dest": "/api/services/$provider.ts?query=$query"
},
{
"src": "/(.*)",