Skip to content

Commit

Permalink
Move from Rome to Biome (#490)
Browse files Browse the repository at this point in the history
  • Loading branch information
damianstasik authored Oct 23, 2023
1 parent e735356 commit 821f86f
Show file tree
Hide file tree
Showing 103 changed files with 1,332 additions and 1,209 deletions.
6 changes: 1 addition & 5 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
{
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
},
"editor.defaultFormatter": "rome.rome",
"typescript.tsdk": "node_modules/typescript/lib"
"editor.defaultFormatter": "biomejs.biome"
}
14 changes: 7 additions & 7 deletions backend/src/album/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { z } from 'zod';
import { router } from '..';
import { procedureWithAuthToken } from '../auth/middleware';
import { getSpotifyApi } from '../spotify';
import { mixpanel } from '../mixpanel';
import { z } from "zod";
import { router } from "..";
import { procedureWithAuthToken } from "../auth/middleware";
import { mixpanel } from "../mixpanel";
import { getSpotifyApi } from "../spotify";

export const albumRouter = router({
byId: procedureWithAuthToken.input(z.string()).query(async (req) => {
const spotifyApi = getSpotifyApi(req.ctx.token.accessToken);

const album = await spotifyApi.getAlbum(req.input, {
market: 'from_token',
market: "from_token",
});

mixpanel.track('get_album', {
mixpanel.track("get_album", {
distinct_id: req.ctx.token.userId,
album_id: req.input,
});
Expand Down
32 changes: 16 additions & 16 deletions backend/src/artist/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { z } from 'zod';
import { router } from '..';
import { procedureWithAuthToken } from '../auth/middleware';
import { getSpotifyApi } from '../spotify';
import { concatLimit } from 'async';
import shuffle from 'lodash/shuffle';
import { mixpanel } from '../mixpanel';
import { concatLimit } from "async";
import shuffle from "lodash/shuffle";
import { z } from "zod";
import { router } from "..";
import { procedureWithAuthToken } from "../auth/middleware";
import { mixpanel } from "../mixpanel";
import { getSpotifyApi } from "../spotify";

export const artistRouter = router({
top: procedureWithAuthToken
.input(
z.object({
page: z.number(),
timeRange: z.enum(['short_term', 'medium_term', 'long_term']),
timeRange: z.enum(["short_term", "medium_term", "long_term"]),
}),
)
.query(async (req) => {
Expand All @@ -23,7 +23,7 @@ export const artistRouter = router({
time_range: req.input.timeRange,
});

mixpanel.track('get_top_artists', {
mixpanel.track("get_top_artists", {
distinct_id: req.ctx.token.userId,
time_range: req.input.timeRange,
page: req.input.page,
Expand All @@ -42,7 +42,7 @@ export const artistRouter = router({
const spotifyApi = getSpotifyApi(req.ctx.token.accessToken);
const artist = await spotifyApi.getArtist(req.input);

mixpanel.track('get_artist', {
mixpanel.track("get_artist", {
distinct_id: req.ctx.token.userId,
artist_id: req.input,
});
Expand All @@ -54,7 +54,7 @@ export const artistRouter = router({
req.input,
);

mixpanel.track('get_artists', {
mixpanel.track("get_artists", {
distinct_id: req.ctx.token.userId,
artist_ids: req.input,
});
Expand All @@ -71,7 +71,7 @@ export const artistRouter = router({
me.body.country, // TODO: this is passed as `country` in the code, but it should be `market`
);

mixpanel.track('get_artist_top_tracks', {
mixpanel.track("get_artist_top_tracks", {
distinct_id: req.ctx.token.userId,
artist_id: req.input,
});
Expand All @@ -82,7 +82,7 @@ export const artistRouter = router({
.input(
z.object({
id: z.string(),
type: z.enum(['album', 'single', 'appears_on']),
type: z.enum(["album", "single", "appears_on"]),
}),
)
.query(async (req) => {
Expand All @@ -93,10 +93,10 @@ export const artistRouter = router({
include_groups: req.input.type,

// @ts-ignore - this is a valid option
market: 'from_token',
market: "from_token",
});

mixpanel.track('get_artist_albums', {
mixpanel.track("get_artist_albums", {
distinct_id: req.ctx.token.userId,
artist_id: req.input.id,
type: req.input.type,
Expand Down Expand Up @@ -143,7 +143,7 @@ export const artistRouter = router({
hasNextPage: false,
};
} finally {
mixpanel.track('get_related_artists_top_tracks', {
mixpanel.track("get_related_artists_top_tracks", {
distinct_id: req.ctx.token.userId,
artist_id: req.input.id,
page: req.input.page,
Expand Down
72 changes: 36 additions & 36 deletions backend/src/auth/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { router, procedure } from '..';
import { getSpotifyApi } from '../spotify';
import { procedureWithAuthToken, withAuthToken } from './middleware';
import * as jwt from 'jsonwebtoken';
import isPast from 'date-fns/isPast';
import { mixpanel } from '../mixpanel';
import { TRPCError } from "@trpc/server";
import isPast from "date-fns/isPast";
import * as jwt from "jsonwebtoken";
import { z } from "zod";
import { procedure, router } from "..";
import { mixpanel } from "../mixpanel";
import { getSpotifyApi } from "../spotify";
import { procedureWithAuthToken, withAuthToken } from "./middleware";

function to<T, U = Error>(
promise: Promise<T>,
Expand All @@ -24,19 +24,19 @@ function to<T, U = Error>(
}

const scopes = [
'user-read-private',
'user-read-recently-played',
'user-read-playback-state',
'user-top-read',
'user-read-currently-playing',
'user-follow-read',
'playlist-read-private',
'user-read-email',
'user-library-read',
'playlist-read-collaborative',
'user-follow-modify',
'user-library-modify',
'streaming',
"user-read-private",
"user-read-recently-played",
"user-read-playback-state",
"user-top-read",
"user-read-currently-playing",
"user-follow-read",
"playlist-read-private",
"user-read-email",
"user-library-read",
"playlist-read-collaborative",
"user-follow-modify",
"user-library-modify",
"streaming",
];

export const authRouter = router({
Expand All @@ -48,11 +48,11 @@ export const authRouter = router({
spotifyApi.setRefreshToken(req.ctx.token.refreshToken);

if (isPast(req.ctx.token.exp)) {
console.log('refreshing access token');
console.log("refreshing access token");

const res = await spotifyApi.refreshAccessToken();

console.log('refreshing res', res);
console.log("refreshing res", res);

const newToken = jwt.sign(
{
Expand All @@ -66,17 +66,17 @@ export const authRouter = router({
},
);

req.ctx.res.cookie('token', newToken, {
path: '/',
req.ctx.res.cookie("token", newToken, {
path: "/",
httpOnly: true,
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 31),
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
});
}
}),
url: procedure.mutation(() => {
const url = getSpotifyApi().createAuthorizeURL(scopes, '');
const url = getSpotifyApi().createAuthorizeURL(scopes, "");

return url;
}),
Expand All @@ -87,7 +87,7 @@ export const authRouter = router({

if (profileError || !profileResult) {
throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
code: "INTERNAL_SERVER_ERROR",
});
}

Expand All @@ -109,7 +109,7 @@ export const authRouter = router({
);

if (codeGrantError || !codeGrantResult) {
throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR' });
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
}

spotifyApi.setAccessToken(codeGrantResult.body.access_token);
Expand All @@ -118,7 +118,7 @@ export const authRouter = router({
const [profileError, profileResult] = await to(spotifyApi.getMe());

if (profileError || !profileResult) {
throw new TRPCError({ code: 'NOT_FOUND' });
throw new TRPCError({ code: "NOT_FOUND" });
}

const token = jwt.sign(
Expand All @@ -133,19 +133,19 @@ export const authRouter = router({
},
);

ctx.res.setCookie('token', token, {
path: '/',
ctx.res.setCookie("token", token, {
path: "/",
httpOnly: true,
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 31),
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
});

mixpanel.people.set(profileResult.body.id, {
$country_code: profileResult.body.country,
});

mixpanel.track('authorize', {
mixpanel.track("authorize", {
distinct_id: profileResult.body.id,
});
}),
Expand Down
18 changes: 9 additions & 9 deletions backend/src/auth/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { TRPCError } from '@trpc/server';
import { TokenExpiredError } from 'jsonwebtoken';
import { middleware, procedure } from '..';
import * as jwt from 'jsonwebtoken';
import { TRPCError } from "@trpc/server";
import { TokenExpiredError } from "jsonwebtoken";
import * as jwt from "jsonwebtoken";
import { middleware, procedure } from "..";

export interface AuthTokenInterface {
accessToken: string;
Expand All @@ -19,7 +19,7 @@ type MiddlewareOptions = {
export const withAuthToken = (options?: MiddlewareOptions) =>
middleware(async ({ ctx, next }) => {
if (!ctx.rawToken) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
throw new TRPCError({ code: "UNAUTHORIZED" });
}

try {
Expand All @@ -36,16 +36,16 @@ export const withAuthToken = (options?: MiddlewareOptions) =>
} catch (e) {
if (e instanceof TokenExpiredError) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: 'token_expired',
code: "UNAUTHORIZED",
message: "token_expired",

cause: e,
});
}

throw new TRPCError({
code: 'BAD_REQUEST',
message: 'malformed_header',
code: "BAD_REQUEST",
message: "malformed_header",

cause: e,
});
Expand Down
10 changes: 5 additions & 5 deletions backend/src/context.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { inferAsyncReturnType } from '@trpc/server';
import { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';
import { parse } from 'cookie';
import { inferAsyncReturnType } from "@trpc/server";
import { CreateFastifyContextOptions } from "@trpc/server/adapters/fastify";
import { parse } from "cookie";

export async function createContext({ req, res }: CreateFastifyContextOptions) {
const cookie = req.headers['cookie'];
const cookie = req.headers.cookie;

const parsedCookie = parse(cookie || '');
const parsedCookie = parse(cookie || "");

if (parsedCookie?.token) {
return {
Expand Down
6 changes: 3 additions & 3 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { initTRPC } from '@trpc/server';
import { Context } from './context';
import EventEmitter from 'node:events';
import EventEmitter from "node:events";
import { initTRPC } from "@trpc/server";
import { Context } from "./context";

const t = initTRPC.context<Context>().create();
export const ee = new EventEmitter();
Expand Down
2 changes: 1 addition & 1 deletion backend/src/mixpanel.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
import Mixpanel from 'mixpanel';
import Mixpanel from "mixpanel";
export const mixpanel = Mixpanel.init(process.env.MIXPANEL_TOKEN);
12 changes: 6 additions & 6 deletions backend/src/player/index.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { router } from '..';
import { procedureWithAuthToken } from '../auth/middleware';
import { mixpanel } from '../mixpanel';
import { router } from "..";
import { procedureWithAuthToken } from "../auth/middleware";
import { mixpanel } from "../mixpanel";

export const playerRouter = router({
queue: procedureWithAuthToken.query(async (req) => {
const res = await fetch('https://api.spotify.com/v1/me/player/queue', {
const res = await fetch("https://api.spotify.com/v1/me/player/queue", {
headers: {
'Content-Type': 'application/json',
"Content-Type": "application/json",
Authorization: `Bearer ${req.ctx.token.accessToken}`,
},
});

const body = await res.json();

mixpanel.track('get_queue', {
mixpanel.track("get_queue", {
distinct_id: req.ctx.token.userId,
});

Expand Down
Loading

0 comments on commit 821f86f

Please sign in to comment.