Verified Commit 8c4bbd94 authored by Chocobozzz's avatar Chocobozzz
Browse files

Refactor model utils

parent a8749f7c
import express from 'express'
import { SortType } from '../models/utils'
const setDefaultSort = setDefaultSortFactory('-createdAt')
const setDefaultVideosSort = setDefaultSortFactory('-publishedAt')
......@@ -7,27 +6,7 @@ const setDefaultVideosSort = setDefaultSortFactory('-publishedAt')
const setDefaultVideoRedundanciesSort = setDefaultSortFactory('name')
const setDefaultSearchSort = setDefaultSortFactory('-match')
function setBlacklistSort (req: express.Request, res: express.Response, next: express.NextFunction) {
const newSort: SortType = { sortModel: undefined, sortValue: '' }
if (!req.query.sort) req.query.sort = '-createdAt'
// Set model we want to sort onto
if (req.query.sort === '-createdAt' || req.query.sort === 'createdAt' ||
req.query.sort === '-id' || req.query.sort === 'id') {
// If we want to sort onto the BlacklistedVideos relation, we won't specify it in the query parameter...
newSort.sortModel = undefined
} else {
newSort.sortModel = 'Video'
}
newSort.sortValue = req.query.sort
req.query.sort = newSort
return next()
}
const setBlacklistSort = setDefaultSortFactory('-createdAt')
// ---------------------------------------------------------------------------
......
......@@ -5,7 +5,7 @@ import { MAbuseMessage, MAbuseMessageFormattable } from '@server/types/models'
import { AbuseMessage } from '@shared/models'
import { AttributesOnly } from '@shared/typescript-utils'
import { AccountModel, ScopeNames as AccountScopeNames } from '../account/account'
import { getSort, throwIfNotValid } from '../utils'
import { getSort, throwIfNotValid } from '../shared'
import { AbuseModel } from './abuse'
@Table({
......
......@@ -34,7 +34,7 @@ import { AttributesOnly } from '@shared/typescript-utils'
import { ABUSE_STATES, CONSTRAINTS_FIELDS } from '../../initializers/constants'
import { MAbuseAdminFormattable, MAbuseAP, MAbuseFull, MAbuseReporter, MAbuseUserFormattable, MUserAccountId } from '../../types/models'
import { AccountModel, ScopeNames as AccountScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account'
import { getSort, throwIfNotValid } from '../utils'
import { getSort, throwIfNotValid } from '../shared'
import { ThumbnailModel } from '../video/thumbnail'
import { ScopeNames as VideoScopeNames, VideoModel } from '../video/video'
import { VideoBlacklistModel } from '../video/video-blacklist'
......
......@@ -2,7 +2,7 @@
import { exists } from '@server/helpers/custom-validators/misc'
import { forceNumber } from '@shared/core-utils'
import { AbuseFilter, AbuseState, AbuseVideoIs } from '@shared/models'
import { buildBlockedAccountSQL, buildDirectionAndField } from '../../utils'
import { buildBlockedAccountSQL, buildSortDirectionAndField } from '../../shared'
export type BuildAbusesQueryOptions = {
start: number
......@@ -157,7 +157,7 @@ function buildAbuseListQuery (options: BuildAbusesQueryOptions, type: 'count' |
}
function buildAbuseOrder (value: string) {
const { direction, field } = buildDirectionAndField(value)
const { direction, field } = buildSortDirectionAndField(value)
return `ORDER BY "abuse"."${field}" ${direction}`
}
......
......@@ -6,7 +6,7 @@ import { AttributesOnly } from '@shared/typescript-utils'
import { AccountBlock } from '../../../shared/models'
import { ActorModel } from '../actor/actor'
import { ServerModel } from '../server/server'
import { createSafeIn, getSort, searchAttribute } from '../utils'
import { createSafeIn, getSort, searchAttribute } from '../shared'
import { AccountModel } from './account'
@Table({
......
......@@ -11,7 +11,7 @@ import { AttributesOnly } from '@shared/typescript-utils'
import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
import { CONSTRAINTS_FIELDS, VIDEO_RATE_TYPES } from '../../initializers/constants'
import { ActorModel } from '../actor/actor'
import { getSort, throwIfNotValid } from '../utils'
import { getSort, throwIfNotValid } from '../shared'
import { VideoModel } from '../video/video'
import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from '../video/video-channel'
import { AccountModel } from './account'
......
......@@ -16,7 +16,7 @@ import {
Table,
UpdatedAt
} from 'sequelize-typescript'
import { ModelCache } from '@server/models/model-cache'
import { ModelCache } from '@server/models/shared/model-cache'
import { AttributesOnly } from '@shared/typescript-utils'
import { Account, AccountSummary } from '../../../shared/models/actors'
import { isAccountDescriptionValid } from '../../helpers/custom-validators/accounts'
......@@ -38,7 +38,7 @@ import { ApplicationModel } from '../application/application'
import { ServerModel } from '../server/server'
import { ServerBlocklistModel } from '../server/server-blocklist'
import { UserModel } from '../user/user'
import { buildSQLAttributes, getSort, throwIfNotValid } from '../utils'
import { buildSQLAttributes, getSort, throwIfNotValid } from '../shared'
import { VideoModel } from '../video/video'
import { VideoChannelModel } from '../video/video-channel'
import { VideoCommentModel } from '../video/video-comment'
......
......@@ -38,7 +38,7 @@ import { ACTOR_FOLLOW_SCORE, CONSTRAINTS_FIELDS, FOLLOW_STATES, SERVER_ACTOR_NAM
import { AccountModel } from '../account/account'
import { ServerModel } from '../server/server'
import { doesExist } from '../shared/query'
import { buildSQLAttributes, createSafeIn, getSort, searchAttribute, throwIfNotValid } from '../utils'
import { buildSQLAttributes, createSafeIn, getSort, searchAttribute, throwIfNotValid } from '../shared'
import { VideoChannelModel } from '../video/video-channel'
import { ActorModel, unusedActorAttributesForAPI } from './actor'
import { InstanceListFollowersQueryBuilder, ListFollowersOptions } from './sql/instance-list-followers-query-builder'
......@@ -225,7 +225,7 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
`WHERE "actorId" = $followerActorId AND "targetActorId" = $actorId AND "state" = 'accepted' ` +
`LIMIT 1`
return doesExist(query, { actorId, followerActorId })
return doesExist(this.sequelize, query, { actorId, followerActorId })
}
static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction): Promise<MActorFollowActorsDefault> {
......
......@@ -22,7 +22,7 @@ import { isActivityPubUrlValid } from '../../helpers/custom-validators/activityp
import { logger } from '../../helpers/logger'
import { CONFIG } from '../../initializers/config'
import { LAZY_STATIC_PATHS, MIMETYPES, WEBSERVER } from '../../initializers/constants'
import { buildSQLAttributes, throwIfNotValid } from '../utils'
import { buildSQLAttributes, throwIfNotValid } from '../shared'
import { ActorModel } from './actor'
@Table({
......
......@@ -17,7 +17,7 @@ import {
} from 'sequelize-typescript'
import { activityPubContextify } from '@server/lib/activitypub/context'
import { getBiggestActorImage } from '@server/lib/actor-image'
import { ModelCache } from '@server/models/model-cache'
import { ModelCache } from '@server/models/shared/model-cache'
import { forceNumber, getLowercaseExtension } from '@shared/core-utils'
import { ActivityIconObject, ActivityPubActorType, ActorImageType } from '@shared/models'
import { AttributesOnly } from '@shared/typescript-utils'
......@@ -55,7 +55,7 @@ import {
import { AccountModel } from '../account/account'
import { getServerActor } from '../application/application'
import { ServerModel } from '../server/server'
import { buildSQLAttributes, isOutdated, throwIfNotValid } from '../utils'
import { buildSQLAttributes, isOutdated, throwIfNotValid } from '../shared'
import { VideoModel } from '../video/video'
import { VideoChannelModel } from '../video/video-channel'
import { ActorFollowModel } from './actor-follow'
......
import { Sequelize } from 'sequelize'
import { ModelBuilder } from '@server/models/shared'
import { parseRowCountResult } from '@server/models/utils'
import { MActorFollowActorsDefault } from '@server/types/models'
import { ActivityPubActorType, FollowState } from '@shared/models'
import { parseRowCountResult } from '../../shared'
import { InstanceListFollowsQueryBuilder } from './shared/instance-list-follows-query-builder'
export interface ListFollowersOptions {
......
import { Sequelize } from 'sequelize'
import { ModelBuilder } from '@server/models/shared'
import { parseRowCountResult } from '@server/models/utils'
import { MActorFollowActorsDefault } from '@server/types/models'
import { ActivityPubActorType, FollowState } from '@shared/models'
import { parseRowCountResult } from '../../shared'
import { InstanceListFollowsQueryBuilder } from './shared/instance-list-follows-query-builder'
export interface ListFollowingOptions {
......
import { Sequelize } from 'sequelize'
import { AbstractRunQuery } from '@server/models/shared'
import { getInstanceFollowsSort } from '@server/models/utils'
import { ActorImageType } from '@shared/models'
import { getInstanceFollowsSort } from '../../../shared'
import { ActorFollowTableAttributes } from './actor-follow-table-attributes'
type BaseOptions = {
......
......@@ -34,7 +34,7 @@ import { CONFIG } from '../../initializers/config'
import { CONSTRAINTS_FIELDS, MIMETYPES } from '../../initializers/constants'
import { ActorModel } from '../actor/actor'
import { ServerModel } from '../server/server'
import { getSort, getVideoSort, parseAggregateResult, throwIfNotValid } from '../utils'
import { getSort, getVideoSort, parseAggregateResult, throwIfNotValid } from '../shared'
import { ScheduleVideoUpdateModel } from '../video/schedule-video-update'
import { VideoModel } from '../video/video'
import { VideoChannelModel } from '../video/video-channel'
......
......@@ -11,7 +11,7 @@ import {
isPluginStableVersionValid,
isPluginTypeValid
} from '../../helpers/custom-validators/plugins'
import { getSort, throwIfNotValid } from '../utils'
import { getSort, throwIfNotValid } from '../shared'
@DefaultScope(() => ({
attributes: {
......
......@@ -4,7 +4,7 @@ import { MServerBlocklist, MServerBlocklistAccountServer, MServerBlocklistFormat
import { ServerBlock } from '@shared/models'
import { AttributesOnly } from '@shared/typescript-utils'
import { AccountModel } from '../account/account'
import { createSafeIn, getSort, searchAttribute } from '../utils'
import { createSafeIn, getSort, searchAttribute } from '../shared'
import { ServerModel } from './server'
enum ScopeNames {
......
......@@ -4,7 +4,7 @@ import { MServer, MServerFormattable } from '@server/types/models/server'
import { AttributesOnly } from '@shared/typescript-utils'
import { isHostValid } from '../../helpers/custom-validators/servers'
import { ActorModel } from '../actor/actor'
import { buildSQLAttributes, throwIfNotValid } from '../utils'
import { buildSQLAttributes, throwIfNotValid } from '../shared'
import { ServerBlocklistModel } from './server-blocklist'
@Table({
......
export * from './abstract-run-query'
export * from './model-builder'
export * from './model-cache'
export * from './query'
export * from './sequelize-helpers'
export * from './sort'
export * from './sql'
export * from './update'
import { BindOrReplacements, QueryTypes } from 'sequelize'
import { sequelizeTypescript } from '@server/initializers/database'
import { BindOrReplacements, Op, QueryTypes, Sequelize } from 'sequelize'
import validator from 'validator'
import { forceNumber } from '@shared/core-utils'
function doesExist (query: string, bind?: BindOrReplacements) {
function doesExist (sequelize: Sequelize, query: string, bind?: BindOrReplacements) {
const options = {
type: QueryTypes.SELECT as QueryTypes.SELECT,
bind,
raw: true
}
return sequelizeTypescript.query(query, options)
return sequelize.query(query, options)
.then(results => results.length === 1)
}
function createSimilarityAttribute (col: string, value: string) {
return Sequelize.fn(
'similarity',
searchTrigramNormalizeCol(col),
searchTrigramNormalizeValue(value)
)
}
function buildWhereIdOrUUID (id: number | string) {
return validator.isInt('' + id) ? { id } : { uuid: id }
}
function parseAggregateResult (result: any) {
if (!result) return 0
const total = forceNumber(result)
if (isNaN(total)) return 0
return total
}
function parseRowCountResult (result: any) {
if (result.length !== 0) return result[0].total
return 0
}
function createSafeIn (sequelize: Sequelize, toEscape: (string | number)[], additionalUnescaped: string[] = []) {
return toEscape.map(t => {
return t === null
? null
: sequelize.escape('' + t)
}).concat(additionalUnescaped).join(', ')
}
function searchAttribute (sourceField?: string, targetField?: string) {
if (!sourceField) return {}
return {
[targetField]: {
// FIXME: ts error
[Op.iLike as any]: `%${sourceField}%`
}
}
}
export {
doesExist
doesExist,
createSimilarityAttribute,
buildWhereIdOrUUID,
parseAggregateResult,
parseRowCountResult,
createSafeIn,
searchAttribute
}
// ---------------------------------------------------------------------------
function searchTrigramNormalizeValue (value: string) {
return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
}
function searchTrigramNormalizeCol (col: string) {
return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment