-
Notifications
You must be signed in to change notification settings - Fork 167
Expand file tree
/
Copy pathstormGlass.ts
More file actions
188 lines (167 loc) · 5.75 KB
/
stormGlass.ts
File metadata and controls
188 lines (167 loc) · 5.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import { InternalError } from '@src/util/errors/internal-error';
import config, { IConfig } from 'config';
// Another way to have similar behaviour to TS namespaces
import * as HTTPUtil from '@src/util/request';
import { TimeUtil } from '@src/util/time';
import CacheUtil from '@src/util/cache';
import logger from '@src/logger';
export interface StormGlassPointSource {
[key: string]: number;
}
export interface StormGlassPoint {
time: string;
readonly waveHeight: StormGlassPointSource;
readonly waveDirection: StormGlassPointSource;
readonly swellDirection: StormGlassPointSource;
readonly swellHeight: StormGlassPointSource;
readonly swellPeriod: StormGlassPointSource;
readonly windDirection: StormGlassPointSource;
readonly windSpeed: StormGlassPointSource;
}
export interface StormGlassForecastResponse {
hours: StormGlassPoint[];
}
export interface ForecastPoint {
time: string;
waveHeight: number;
waveDirection: number;
swellDirection: number;
swellHeight: number;
swellPeriod: number;
windDirection: number;
windSpeed: number;
}
/**
* This error type is used when a request reaches out to the StormGlass API but returns an error
*/
export class StormGlassUnexpectedResponseError extends InternalError {
constructor(message: string) {
super(message);
}
}
/**
* This error type is used when something breaks before the request reaches out to the StormGlass API
* eg: Network error, or request validation error
*/
export class ClientRequestError extends InternalError {
constructor(message: string) {
const internalMessage =
'Unexpected error when trying to communicate to StormGlass';
super(`${internalMessage}: ${message}`);
}
}
export class StormGlassResponseError extends InternalError {
constructor(message: string) {
const internalMessage =
'Unexpected error returned by the StormGlass service';
super(`${internalMessage}: ${message}`);
}
}
/**
* We could have proper type for the configuration
*/
const stormglassResourceConfig: IConfig = config.get(
'App.resources.StormGlass'
);
export class StormGlass {
readonly stormGlassAPIParams =
'swellDirection,swellHeight,swellPeriod,waveDirection,waveHeight,windDirection,windSpeed';
readonly stormGlassAPISource = 'noaa';
constructor(
protected request = new HTTPUtil.Request(),
protected cacheUtil = CacheUtil
) {}
public async fetchPoints(lat: number, lng: number): Promise<ForecastPoint[]> {
const cachedForecastPoints = this.getForecastPointsFromCache(
this.getCacheKey(lat, lng)
);
if (!cachedForecastPoints) {
const forecastPoints = await this.getForecastPointsFromApi(lat, lng);
this.setForecastPointsInCache(this.getCacheKey(lat, lng), forecastPoints);
return forecastPoints;
}
return cachedForecastPoints;
}
protected async getForecastPointsFromApi(
lat: number,
lng: number
): Promise<ForecastPoint[]> {
const endTimestamp = TimeUtil.getUnixTimeForAFutureDay(1);
try {
const response = await this.request.get<StormGlassForecastResponse>(
`${stormglassResourceConfig.get(
'apiUrl'
)}/weather/point?lat=${lat}&lng=${lng}¶ms=${
this.stormGlassAPIParams
}&source=${this.stormGlassAPISource}&end=${endTimestamp}`,
{
headers: {
Authorization: stormglassResourceConfig.get('apiToken'),
},
}
);
return this.normalizeResponse(response.data);
} catch (err: unknown) {
if (err instanceof Error && HTTPUtil.Request.isRequestError(err)) {
const error = HTTPUtil.Request.extractErrorData(err);
throw new StormGlassResponseError(
`Error: ${JSON.stringify(error.data)} Code: ${error.status}`
);
}
/**
* All the other errors will fallback to a generic client error
*/
throw new ClientRequestError(JSON.stringify(err));
}
}
protected getForecastPointsFromCache(
key: string
): ForecastPoint[] | undefined {
const forecastPointsFromCache = this.cacheUtil.get<ForecastPoint[]>(key);
if (!forecastPointsFromCache) {
return;
}
logger.info(`Using cache to return forecast points for key: ${key}`);
return forecastPointsFromCache;
}
private getCacheKey(lat: number, lng: number): string {
return `forecast_points_${lat}_${lng}`;
}
private setForecastPointsInCache(
key: string,
forecastPoints: ForecastPoint[]
): boolean {
logger.info(`Updating cache to return forecast points for key: ${key}`);
return this.cacheUtil.set(
key,
forecastPoints,
stormglassResourceConfig.get('cacheTtl')
);
}
private normalizeResponse(
points: StormGlassForecastResponse
): ForecastPoint[] {
return points.hours.filter(this.isValidPoint.bind(this)).map((point) => ({
swellDirection: point.swellDirection[this.stormGlassAPISource],
swellHeight: point.swellHeight[this.stormGlassAPISource],
swellPeriod: point.swellPeriod[this.stormGlassAPISource],
time: point.time,
waveDirection: point.waveDirection[this.stormGlassAPISource],
waveHeight: point.waveHeight[this.stormGlassAPISource],
windDirection: point.windDirection[this.stormGlassAPISource],
windSpeed: point.windSpeed[this.stormGlassAPISource],
}));
}
private isValidPoint(point: Partial<StormGlassPoint>): boolean {
return !!(
point.time &&
point.swellDirection?.[this.stormGlassAPISource] &&
point.swellHeight?.[this.stormGlassAPISource] &&
point.swellPeriod?.[this.stormGlassAPISource] &&
point.waveDirection?.[this.stormGlassAPISource] &&
point.waveHeight?.[this.stormGlassAPISource] &&
point.windDirection?.[this.stormGlassAPISource] &&
point.windSpeed?.[this.stormGlassAPISource]
);
}
}