Skip to content

Commit

Permalink
fix: 💚 eslint fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
ignazio-bovo committed Aug 7, 2023
1 parent e1e8b2a commit 79db8f1
Show file tree
Hide file tree
Showing 15 changed files with 69 additions and 72 deletions.
16 changes: 16 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "lint",
"problemMatcher": [],
"label": "npm: lint",
"detail": "eslint --ext .ts ./src",
"group": {
"kind": "test",
"isDefault": true
}
}
]
}
3 changes: 0 additions & 3 deletions schema/events.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -135,9 +135,6 @@ type NftIssuedEventData {

"NFT's initial owner."
nftOwner: NftOwner!

"init transactional status"
transactionalStatus: TransactionalStatus!
}

# Atlas use-case: `GetNftActivities`, `GetNftHistory`
Expand Down
1 change: 0 additions & 1 deletion src/mappings/content/commentsAndReactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import {
CommentTextUpdatedEventData,
Event,
MemberRecipient,
Membership,
MetaprotocolTransactionResult,
MetaprotocolTransactionResultCommentCreated,
MetaprotocolTransactionResultCommentDeleted,
Expand Down
1 change: 0 additions & 1 deletion src/mappings/content/metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ import {
ASSETS_MAP,
EntityAssetProps,
EntityAssetsMap,
getAccountForMember,
getChannelOwnerAccount,
MetaNumberProps,
} from './utils'
Expand Down
8 changes: 0 additions & 8 deletions src/mappings/content/nft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
englishAuctionNotifiers,
findTopBid,
finishAuction,
getChannelOwnerAccount,
getChannelTitle,
getCurrentAuctionFromVideo,
getNftOwnerMemberId,
Expand Down Expand Up @@ -44,9 +43,7 @@ import {
TransactionalStatusIdle,
TransactionalStatusInitiatedOfferToMember,
Video,
Channel,
MemberRecipient,
NftOffered,
NotificationData,
NewAuction,
NewNftOnSale,
Expand All @@ -73,7 +70,6 @@ import {
timedAuctionExpiredLink,
timedAuctionExpiredText,
} from '../../utils/notification'
import { channel } from 'diagnostics_channel'

export async function processOpenAuctionStartedEvent({
overlay,
Expand Down Expand Up @@ -599,9 +595,6 @@ export async function processOpenAuctionBidAcceptedEvent({

export async function processOfferStartedEvent({
overlay,
block,
indexInBlock,
extrinsicHash,
event: {
asV1000: [videoId, , memberId, price],
},
Expand All @@ -628,7 +621,6 @@ export async function processOfferAcceptedEvent({
}: EventHandlerContext<'Content.OfferAccepted'>): Promise<void> {
// load NFT
const nft = await overlay.getRepository(OwnedNft).getByIdOrFail(videoId.toString())
const previousNftOwnerId = await getNftOwnerMemberId(overlay, nft.owner)

// read member from offer
const memberId = (nft.transactionalStatus as TransactionalStatusInitiatedOfferToMember).member
Expand Down
27 changes: 11 additions & 16 deletions src/mappings/content/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,11 @@ import {
NotificationData,
NewAuctionBid,
ChannelRecipient,
Notification,
NotificationType,
OpenAuctionWon,
OpenAuctionLost,
EnglishAuctionWon,
EnglishAuctionLost,
RoyaltyPaid,
} from '../../model'
import { criticalError } from '../../utils/misc'
import { EntityManagerOverlay, Flat } from '../../utils/overlay'
Expand All @@ -82,18 +80,15 @@ import {
higherBidPlacedLink,
nftBidOutbidText,
nftBidReceivedText,
nftRoyaltyPaymentReceivedText,
openAuctionBidLostText,
openAuctionBidWonText,
openAuctionLostLink,
openAuctionWonLink,
royaltiesReceivedLink,
timedAuctionBidLostText,
timedAuctionBidWonText,
timedAuctionLostLink,
timedAuctionWonLink,
} from '../../utils/notification'
import { type } from 'os'

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type AsDecoded<MetaClass> = MetaClass extends { create: (props?: infer I) => any }
Expand Down Expand Up @@ -263,7 +258,6 @@ export async function processNft(
actor: parseContentActor(issuer),
nft: nft.id,
nftOwner: nft.owner,
transactionalStatus: nft.transactionalStatus!,
}),
})

Expand Down Expand Up @@ -675,9 +669,9 @@ export async function getFollowersAccountsForChannel(
): Promise<Account[]> {
const followers = await overlay.getEm().getRepository(ChannelFollow).findBy({ channelId })

const followersUserIds = await Promise.all(
followers.filter((follower) => follower.userId).map((follower) => follower.userId!)
)
const followersUserIds = followers
.filter((follower) => follower?.userId)
.map((follower) => follower.userId as string)

const followersAccounts = await Promise.all(
followersUserIds.map(
Expand Down Expand Up @@ -815,9 +809,9 @@ export async function notifyBiddersOnAuctionCompletion(
},
event: Event
) {
for (const bidderId of biddersMemberIds.map((id) => id)) {
for (const bidderId of biddersMemberIds.filter((id) => id)) {
const account = await getAccountForMember(overlay.getEm(), bidderId)
const memberHandle = (await memberHandleById(overlay, bidderId!)) || ''
const memberHandle = (await memberHandleById(overlay, bidderId)) || ''
const notification =
bidderId === winnerId.toString() ? notifier.won(memberHandle) : notifier.lost(memberHandle)

Expand All @@ -829,6 +823,12 @@ export type PageLinkData = {
em: EntityManager
videoId: string
}

export type AuctionNotifiers = {
won: (memberHandle: string) => NotificationType
lost: (memberHandle: string) => NotificationType
}

export const openAuctionNotifiers = async (
{ em, videoId }: PageLinkData,
videoTitle: string
Expand Down Expand Up @@ -859,11 +859,6 @@ export const openAuctionNotifiers = async (
}
}

export type AuctionNotifiers = {
won: (memberHandle: string) => NotificationType
lost: (memberHandle: string) => NotificationType
}

export const englishAuctionNotifiers = async (
{ em, videoId }: PageLinkData,
videoTitle: string
Expand Down
8 changes: 1 addition & 7 deletions src/mappings/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,7 @@ import { metaToObject } from '@joystream/metadata-protobuf/utils'
import { AnyMetadataClass, DecodedMetadataObject } from '@joystream/metadata-protobuf/types'
import { Logger } from '../logger'
import { SubstrateBlock } from '@subsquid/substrate-processor'
import {
Event,
MetaprotocolTransactionResultFailed,
NftActivity,
NftHistoryEntry,
Account,
} from '../model'
import { Event, MetaprotocolTransactionResultFailed, NftActivity, NftHistoryEntry } from '../model'
import { encodeAddress } from '@polkadot/util-crypto'
import { EntityManagerOverlay } from '../utils/overlay'
import { Bytes } from '@polkadot/types/primitive'
Expand Down
10 changes: 5 additions & 5 deletions src/model/generated/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,6 @@ export * from "./_nftOwnerChannel"
export * from "./_nftOwnerMember"
export * from "./_englishAuctionStartedEventData"
export * from "./_nftIssuedEventData"
export * from "./_transactionalStatus"
export * from "./_transactionalStatusIdle"
export * from "./_transactionalStatusInitiatedOfferToMember"
export * from "./_transactionalStatusBuyNow"
export * from "./_transactionalStatusAuction"
export * from "./_nftOfferedEventData"
export * from "./_auctionBidMadeEventData"
export * from "./_auctionBidCanceledEventData"
Expand Down Expand Up @@ -169,6 +164,11 @@ export * from "./_avatarObject"
export * from "./_avatarUri"
export * from "./membership.model"
export * from "./ownedNft.model"
export * from "./_transactionalStatus"
export * from "./_transactionalStatusIdle"
export * from "./_transactionalStatusInitiatedOfferToMember"
export * from "./_transactionalStatusBuyNow"
export * from "./_transactionalStatusAuction"
export * from "./auction.model"
export * from "./_auctionType"
export * from "./_auctionTypeEnglish"
Expand Down
2 changes: 1 addition & 1 deletion src/server-extension/resolvers/AccountResolver/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import 'reflect-metadata'
import { Query, Resolver, Mutation, UseMiddleware, Ctx, Info, Args } from 'type-graphql'
import { Query, Resolver, UseMiddleware, Ctx, Info } from 'type-graphql'
import { EntityManager } from 'typeorm'
import { AccountOnly } from '../middleware'
import { AccountData, FollowedChannel } from './types'
Expand Down
2 changes: 1 addition & 1 deletion src/server-extension/resolvers/AccountResolver/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Field, ObjectType, ArgsType } from 'type-graphql'
import { Field, ObjectType } from 'type-graphql'

@ObjectType()
export class FollowedChannel {
Expand Down
2 changes: 1 addition & 1 deletion src/server-extension/resolvers/AdminResolver/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ import { parseObjectTree } from '@subsquid/openreader/lib/opencrud/tree'
import { getResolveTree } from '@subsquid/openreader/lib/util/resolve-tree'
import { EntityByIdQuery } from '@subsquid/openreader/lib/sql/query'
import { getObjectSize } from '@subsquid/openreader/lib/limit.size'
import { VideoHero, VideosConnection } from '../baseTypes'
import { VideoHero } from '../baseTypes'
import { model } from '../model'
import { ed25519PairFromString, ed25519Sign } from '@polkadot/util-crypto'
import { u8aToHex, hexToU8a, isHex } from '@polkadot/util'
Expand Down
13 changes: 7 additions & 6 deletions src/server-extension/resolvers/ChannelsResolver/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,13 +227,14 @@ export class ChannelsResolver {

const ownerAccount = await getChannelOwnerAccount(em, channel)
if (ownerAccount) {
const { account: followerAccount } = ctx // non-null because of @UseMiddleware(AccountOnly)
if (ctx.account === undefined) {
// account not null because of the UseMiddleware(AccountOnly) decorator
throw new Error('Account not specified')
}
const followerAccount = ctx.account as Account
const followerHandle =
(
await em
.getRepository(Membership)
.findOneByOrFail({ id: followerAccount!.membershipId })
)?.handle || ''
(await em.getRepository(Membership).findOneByOrFail({ id: followerAccount.membershipId }))
?.handle || ''
const linkPage = await newChannelFollowerLink(em, followerHandle)
const channelTitle = channel.title || ''
await addNotification(
Expand Down
14 changes: 8 additions & 6 deletions src/server-extension/resolvers/NotificationResolver/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { EntityManager } from 'typeorm'
import { AccountOnly } from '../middleware'
import { Context } from '../../check'
import { withHiddenEntities } from '../../../utils/sql'
import { Notification, NotificationPreference, Read } from '../../../model'
import { Account, Notification, NotificationPreference, Read } from '../../../model'
import {
AccountNotificationPreferencesInput,
AccountNotificationPreferencesOutput,
Expand All @@ -29,7 +29,7 @@ export class NotificationResolver {
return withHiddenEntities(em, async () => {
const notificationsReadIds: string[] = []
for (const notificationId of notificationIds.filter((id) => id)) {
const notification = await em.getRepository(Notification).findOneBy({ id: notificationId! })
const notification = await em.getRepository(Notification).findOneBy({ id: notificationId })
if (notification?.accountId) {
if (notification.accountId !== ctx.accountId) {
throw new Error('This notification cannot be read from this account')
Expand All @@ -55,10 +55,12 @@ export class NotificationResolver {
const em = await this.em()

return withHiddenEntities(em, async () => {
const account = ctx.account
if (!account) {
throw new Error('Account not found')
if (ctx.account === undefined) {
// account not null because of the UseMiddleware(AccountOnly) decorator
throw new Error('Account not specified')
}
const account = ctx.account as Account // avoid ctx.account! due to eslint

maybeUpdateNotificationPreference(
newPreferences.channelExcludedFromAppNotificationEnabled,
account.notificationPreferences.channelExcludedFromAppNotificationEnabled
Expand Down Expand Up @@ -189,7 +191,7 @@ export class NotificationResolver {
)
await em.save(account)

return toOutputGQL(account!.notificationPreferences)
return toOutputGQL(account.notificationPreferences)
})
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/utils/notification/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,22 +133,22 @@ export async function addNotification(
const notificationChainTag = event ? 'OffChainNotification' : 'OnChainNotification'
// create notification as disabled = true
const { inAppEnabled, emailEnabled } = preferencesForNotification(
account!.notificationPreferences,
account.notificationPreferences,
notificationType
)
// create notification (for the notification center)
const nextNotificationId = await getNextIdForEntity(em, notificationChainTag)
const notification = new Notification({
id: notificationChainTag + '-' + nextNotificationId.toString(),
accountId: account!.id,
accountId: account.id,
notificationType,
eventId: event?.id,
status: new Unread(),
})

// deliver via mail if enabled
if (emailEnabled) {
await deliverNotificationViaEmail(em, account!, notification)
await deliverNotificationViaEmail(em, account, notification)
}

// deliver via in app if enabled
Expand Down
28 changes: 15 additions & 13 deletions src/utils/offchainState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,12 @@ function migrateExportDataToV300(data: ExportedData): ExportedData {

function migrateExportDataToV310(data: ExportedData): ExportedData {
// account will find himself with all notification pref. enabled by default
data.Account?.values.map((account) => {
data.Account?.values.forEach((account) => {
account.notificationPreferences = defaultNotificationPreferences()
})

// setting channel native Orion verification status to false
data.Channel?.values.map((channel) => {
data.Channel?.values.forEach((channel) => {
channel.isVerified = false
})

Expand Down Expand Up @@ -275,17 +275,19 @@ export class OffchainState {
}

private async migrateCounters(exportedVersion: string, em: EntityManager): Promise<void> {
Object.entries(this.globalCountersMigration)
.sort(([a], [b]) => this.versionToNumber(a) - this.versionToNumber(b)) // sort in increasing order
.forEach(([version, counters]) => {
if (this.versionToNumber(exportedVersion) < this.versionToNumber(version)) {
this.logger.info(`Migrating global counters to version ${version}`)
counters.forEach(async (entityName) => {
// build query that gets the entityName with the highest id
const latestId = await em.query(`SELECT id FROM ${entityName} ORDER BY id DESC LIMIT 1`)
await em.save(new NextEntityId({ entityName, nextId: Number(latestId) + 1 }))
})
const migrationData = Object.entries(this.globalCountersMigration).sort(
([a], [b]) => this.versionToNumber(a) - this.versionToNumber(b)
) // sort in increasing order

for (const [version, counters] of migrationData) {
if (this.versionToNumber(exportedVersion) < this.versionToNumber(version)) {
this.logger.info(`Migrating global counters to version ${version}`)
for (const entityName of counters) {
// build query that gets the entityName with the highest id
const latestId = await em.query(`SELECT id FROM ${entityName} ORDER BY id DESC LIMIT 1`)
await em.save(new NextEntityId({ entityName, nextId: Number(latestId) + 1 }))
}
})
}
}
}
}

0 comments on commit 79db8f1

Please sign in to comment.