Skip to content

Commit

Permalink
Merge pull request #119 from ineshbose/issue/118-setup_ngrok_locally
Browse files Browse the repository at this point in the history
Dev environment change
  • Loading branch information
ineshbose committed Feb 19, 2022
2 parents 9a425de + ff89c4f commit 10695f9
Show file tree
Hide file tree
Showing 23 changed files with 613 additions and 387 deletions.
8 changes: 8 additions & 0 deletions src/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,16 @@ module.exports = {
ignorePatterns: ['backend', 'env'],
rules: {
'import/namespace': 'off',
'import/order': 'error',
'import/extensions': 'off',
'import/no-unresolved': [2, { ignore: ['env$'] }],
'no-use-before-define': 'off',
'@typescript-eslint/no-use-before-define': 'off',
'prettier/prettier': 'error',
},
settings: {
react: {
version: 'detect',
},
},
};
8 changes: 4 additions & 4 deletions src/app/api/auth.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import axios, { AxiosError, AxiosRequestConfig } from 'axios';
import { axiosInstance } from '.';
import { CLIENT_ID, CLIENT_SECRET } from 'react-native-dotenv';
import { CLIENT_ID, CLIENT_SECRET } from '../../env';
import { AuthError, AuthToken } from '../types/api';
import { storeObject, getObject, removeItem } from './store';
import { axiosInstance } from '.';

const API_PATH = '/auth/o/';

Expand Down Expand Up @@ -59,7 +59,7 @@ export const getToken = async (
export const refreshToken = async (authToken?: AuthToken) => {
try {
if (!authToken) {
authToken = (await getObject('auth_token')) as AuthToken;
authToken = await getObject<AuthToken>('auth_token');
}

const response = await axiosInstance.post<AuthToken>(`${API_PATH}token/`, {
Expand All @@ -82,7 +82,7 @@ export const refreshToken = async (authToken?: AuthToken) => {
export const revokeToken = async (authToken?: AuthToken) => {
try {
if (!authToken) {
authToken = (await getObject('auth_token')) as AuthToken;
authToken = await getObject<AuthToken>('auth_token');
}

await axiosInstance.post<AuthToken>(`${API_PATH}revoke_token/`, {
Expand Down
2 changes: 1 addition & 1 deletion src/app/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import axios, { Method } from 'axios';
import { API_BASE } from 'react-native-dotenv';
import { API_BASE } from '../../env';
import { CreateData, FetchData, GenericModel, UpdateData } from '../types/api';

type UnrequiredGM = Partial<GenericModel>;
Expand Down
2 changes: 1 addition & 1 deletion src/app/api/items.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { makeRequest } from '.';
import { CreateData, PortionItem, TrackItem, UpdateData } from '../types/api';
import { makeRequest } from '.';

const API_PATH = '/trackitem/';

Expand Down
2 changes: 1 addition & 1 deletion src/app/api/journals.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { makeRequest } from '.';
import { CreateData, Journal, UpdateData } from '../types/api';
import { makeRequest } from '.';

const API_PATH = '/journals/';

Expand Down
2 changes: 1 addition & 1 deletion src/app/api/logs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { makeRequest } from '.';
import { CreateData, UpdateData, UserLog } from '../types/api';
import { makeRequest } from '.';

const API_PATH = '/userlogs/';

Expand Down
2 changes: 1 addition & 1 deletion src/app/api/resources.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { axiosInstance, makeRequest } from '.';
import { Resource, UpdateData } from '../types/api';
import { axiosInstance, makeRequest } from '.';

const API_PATH = '/resources/';

Expand Down
7 changes: 6 additions & 1 deletion src/app/api/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export const storeData = async (key: string, value: any) => {
return await AsyncStorage.setItem(`@${key}`, value);
} catch (e) {
// saving error
throw e;
}
};

Expand All @@ -14,6 +15,7 @@ export const storeObject = async (key: string, value: object) => {
return await AsyncStorage.setItem(`@${key}`, jsonValue);
} catch (e) {
// saving error
throw e;
}
};

Expand All @@ -23,15 +25,17 @@ export const getData = async (key: string, _default?: string) => {
return value !== null ? value : _default;
} catch (e) {
// error reading value
throw e;
}
};

export const getObject = async (key: string) => {
export const getObject = async <T>(key: string): Promise<T> => {
try {
const jsonValue = await AsyncStorage.getItem(`@${key}`);
return jsonValue !== null ? JSON.parse(jsonValue) : null;
} catch (e) {
// error reading value
throw e;
}
};

Expand All @@ -40,5 +44,6 @@ export const removeItem = async (key: string) => {
return await AsyncStorage.removeItem(`@${key}`);
} catch (e) {
// error removing value
throw e;
}
};
4 changes: 2 additions & 2 deletions src/app/api/user.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { makeRequest } from '.';
import { CreateData, UpdateData, User } from '../types/api';
import { makeRequest } from '.';

const API_PATH = '/users/';
// const API_PATH = (extraPath: TemplateStringsArray) => `/users/${extraPath}/`;

export const getUser = async () => makeRequest<User>(API_PATH);
export const getUser = async () => <User>(<unknown>makeRequest<User>(API_PATH));

export const createUser = async (
props: CreateData<User, 'email'> & { password: string }
Expand Down
2 changes: 1 addition & 1 deletion src/app/components/FAB/MainButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import {
View,
} from 'react-native';
import { Button, Icon } from '@ui-kitten/components';
import ActionItem from './ActionItem';
import { MainButtonProps } from '../../types/FAB';
import { RootActionParamList } from '../../types/navigation';
import ActionItem from './ActionItem';

const DEFAULT_SHADOW_PROPS = {
shadowOpacity: 0.35,
Expand Down
9 changes: 5 additions & 4 deletions src/app/contexts/AppContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ export const ContextProvider = ({ children }: ChildComponents) => {
React.useEffect(() => {
const loadToken = async () => {
try {
const authData = (await getObject('auth_token')) as AuthToken;
const authData = await getObject<AuthToken>('auth_token');
if (authData) {
authData.interceptor = addRefreshInterceptor(signOut);
await updateAuthHeaderAndStore(authData);
const userData = (await getUser()) as User;
const userData = await getUser();
setUser(userData);
}
setAuthToken(authData);
Expand All @@ -53,12 +53,13 @@ export const ContextProvider = ({ children }: ChildComponents) => {
};

loadToken().then(() => setLoading(false));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

const signIn = async (email: string, password: string) => {
try {
const authData = (await getToken(email, password, signOut)) as AuthToken;
const userData = (await getUser()) as User;
const authData = await getToken(email, password, signOut);
const userData = await getUser();
setUser(userData);
setAuthToken(authData);
} catch (e) {
Expand Down
8 changes: 4 additions & 4 deletions src/app/navigation/RootNavigator.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import React from 'react';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import BottomTabNavigator from './BottomTabNavigator';
import AuthNavigator from './AuthNavigator';
import { useAppContext } from '../contexts';
import { RootLinkParamList } from '../types/navigation';
import { SafeAreaView, StyleSheet } from 'react-native';
import { Layout, Spinner, Text } from '@ui-kitten/components';
import { useAppContext } from '../contexts';
import { RootLinkParamList } from '../types/navigation';
import BottomTabNavigator from './BottomTabNavigator';
import AuthNavigator from './AuthNavigator';

const Root = createNativeStackNavigator<RootLinkParamList>();

Expand Down
2 changes: 1 addition & 1 deletion src/app/navigation/StackNavigator.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import React from 'react';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import RootNavigator from './RootNavigator';
import NotFoundScreen from '../screens/NotFoundScreen';
import ModalScreen from '../screens/ModalScreen';
import { RootStackParamList } from '../types/navigation';
import RootNavigator from './RootNavigator';

const Stack = createNativeStackNavigator<RootStackParamList>();

Expand Down
4 changes: 2 additions & 2 deletions src/app/screens/Auth/AuthForm.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import React from 'react';
import Logo from './Logo';
import { KeyboardAvoidingView, View } from 'react-native';
import { Button, Input, Layout } from '@ui-kitten/components';
import { AuthError } from '../../types/api';
import styles from './FormStyle';
import { useThemeContext } from '../../contexts';
import styles from './FormStyle';
import Logo from './Logo';

type FormProps = {
children: (Input | JSX.Element | undefined)[];
Expand Down
2 changes: 1 addition & 1 deletion src/app/screens/Auth/RegisterForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import React from 'react';
import { Button, CheckBox, Input, Text } from '@ui-kitten/components';
import { RootAuthScreenProps } from '../../types/navigation';
import { useAppContext } from '../../contexts';
import { FormError } from '../../types/api';
import AuthForm from './AuthForm';
import styles, { passwordAccessory, SwitchForm } from './FormStyle';
import { FormError } from '../../types/api';

export default function RegisterForm({
navigation,
Expand Down
2 changes: 1 addition & 1 deletion src/app/screens/BottomTab/StatsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import React from 'react';
import { SafeAreaView, ScrollView, StyleSheet } from 'react-native';
import { Calendar, Layout, Tab, TabBar } from '@ui-kitten/components';
import { LineChart, PieChart } from 'react-native-chart-kit';
import { useAppContext, useThemeContext } from '../../contexts';
import { AbstractChartConfig } from 'react-native-chart-kit/dist/AbstractChart';
import { useAppContext, useThemeContext } from '../../contexts';
import { PortionItem, TrackItem, TrackItems } from '../../types/api';
import Display from '../../constants/Display';

Expand Down
2 changes: 1 addition & 1 deletion src/app/types/FAB.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { TextProps, TextStyle, ViewStyle } from 'react-native';
import { IconOptions } from '.';
import { RootActionParamList } from './navigation';
import { IconOptions } from '.';

export type Actions = keyof RootActionParamList;

Expand Down
10 changes: 1 addition & 9 deletions src/app/types/env.d.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1 @@
declare module 'react-native-dotenv' {
export const DEBUG: boolean;
export const SECRET_KEY: string;
export const ADMINS: string[];
export const ALLOWED_HOSTS: string[];
export const API_BASE: string;
export const CLIENT_ID: string;
export const CLIENT_SECRET: string;
}
declare module '*env';
6 changes: 0 additions & 6 deletions src/babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,5 @@ module.exports = function (api) {

return {
presets: ['babel-preset-expo'],
plugins: [
[
'module:react-native-dotenv',
{ moduleName: 'react-native-dotenv', path: `${__dirname}/.env` },
],
],
};
};
40 changes: 22 additions & 18 deletions src/metro.config.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
// Learn more https://docs.expo.io/guides/customizing-metro
const { getDefaultConfig } = require('expo/metro-config');
const path = require('path');

const crypto = require('crypto');
const fs = require('fs');
const { getDefaultConfig } = require('expo/metro-config');
const setEnv = require('./set-env');

// Find the workspace root, this can be replaced with `find-yarn-workspace-root`
const workspaceRoot = path.resolve(__dirname, '..');
const projectRoot = __dirname;
module.exports = async () => {
await setEnv.start();
// Find the workspace root, this can be replaced with `find-yarn-workspace-root`
const workspaceRoot = path.resolve(__dirname, '..');
const projectRoot = __dirname;

const config = getDefaultConfig(projectRoot);
const config = getDefaultConfig(projectRoot);

// Watch all files within the monorepo
config.watchFolders = [workspaceRoot];
// Let Metro know where to resolve packages, and in what order
config.resolver.nodeModulesPaths = [
path.resolve(projectRoot, 'node_modules'),
path.resolve(workspaceRoot, 'node_modules'),
];
// Watch all files within the monorepo
config.watchFolders = [workspaceRoot];
// Let Metro know where to resolve packages, and in what order
config.resolver.nodeModulesPaths = [
path.resolve(projectRoot, 'node_modules'),
path.resolve(workspaceRoot, 'node_modules'),
];

// Reread env file
let hash = crypto.createHash('sha256');
hash.update(fs.readFileSync(path.resolve(projectRoot, '.env')));
config.cacheVersion = hash.digest('hex');
config.resetCache = true;
// Reread env file
let hash = crypto.createHash('sha256');
hash.update(fs.readFileSync(path.resolve(projectRoot, '.env')));
config.cacheVersion = hash.digest('hex');
config.resetCache = true;

module.exports = config;
return config;
};
5 changes: 3 additions & 2 deletions src/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"@react-navigation/native-stack": "^6.5.0",
"@ui-kitten/components": "^5.1.1",
"axios": "^0.26.0",
"dotenv": "^16.0.0",
"expo": "~44.0.6",
"expo-asset": "~8.4.3",
"expo-constants": "~13.0.2",
Expand All @@ -32,11 +33,11 @@
"expo-splash-screen": "~0.14.2",
"expo-status-bar": "~1.2.0",
"expo-web-browser": "~10.1.1",
"ngrok": "^4.3.0",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-native": "0.67.2",
"react-native": "0.64.3",
"react-native-chart-kit": "^6.12.0",
"react-native-dotenv": "^3.3.1",
"react-native-markdown-display": "^7.0.0-alpha.2",
"react-native-safe-area-context": "3.3.2",
"react-native-screens": "~3.10.1",
Expand Down
39 changes: 39 additions & 0 deletions src/set-env.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const fs = require('fs');
const ngrok = require('ngrok');
const dotenv = require('dotenv');

const getPort = (url) => {
url = (url.match(/^(([a-z]+:)?(\/\/)?[^\/]+).*$/) || ['', ''])[1] || url;
var parts = url.split(':'),
port = parseInt(parts[parts.length - 1], 10);
if (parts[0] === 'http' && (isNaN(port) || parts.length < 3)) {
return 80;
}
if (parts[0] === 'https' && (isNaN(port) || parts.length < 3)) {
return 443;
}
return parts.length === 1 || isNaN(port) ? 80 : port;
};

const writeToFile = (envData) =>
fs.writeFileSync(
`${__dirname}/env/index.ts`,
`export const {${Object.keys(envData).join(', ')}} = ${JSON.stringify(
envData
)};`
);

const start = (file = `${__dirname}/.env`) => {
const env = dotenv.parse(fs.readFileSync(file, 'utf-8'));
const port = getPort(env.API_BASE);
if (env.DEBUG.toLowerCase() === 'true' && port) {
ngrok.connect(port).then((value) => {
env.API_BASE = `${value}${env.API_BASE.split(`${port}`)[1]}`;
writeToFile(env);
});
} else {
writeToFile(env);
}
};

module.exports = { start };
Loading

0 comments on commit 10695f9

Please sign in to comment.