Best JavaScript code snippet using argos
github.js
Source:github.js
1/* eslint-disable no-await-in-loop */2import {3 getAuthorizationOctokit,4 getUserOctokit,5 getInstallationOctokit,6} from 'modules/github/client'7import {8 Installation,9 Organization,10 Repository,11 User,12 UserOrganizationRight,13 UserRepositoryRight,14 UserInstallationRight,15 InstallationRepositoryRight,16} from 'models'17import config from 'config'18export async function getOrCreateInstallation(payload) {19 const installation = await Installation.query()20 .where({ githubId: payload.githubId })21 .first()22 if (installation) return installation23 return Installation.query().insertAndFetch(payload)24}25async function checkAccessTokenValidity(accessToken) {26 try {27 await getAuthorizationOctokit().oauthAuthorizations.checkAuthorization({28 access_token: accessToken,29 client_id: config.get('github.clientId'),30 })31 } catch (error) {32 if (error.status === 404) {33 return false34 }35 throw error36 }37 return true38}39const OWNER_ORGANIZATION = 'Organization'40const OWNER_USER = 'User'41export class GitHubSynchronizer {42 constructor(synchronization) {43 this.synchronization = synchronization44 this.repositories = []45 this.organizationIds = []46 }47 async synchronizeAppRepositories(installationId) {48 const options = this.octokit.apps.listRepos.endpoint.DEFAULTS49 const githubRepositories = await this.octokit.paginate(options)50 const { repositories, organizations } = await this.synchronizeRepositories(51 githubRepositories,52 )53 await this.synchronizeInstallationRepositoryRights(54 repositories,55 installationId,56 )57 return { repositories, organizations }58 }59 async synchronizeUserInstallationRepositories(installation) {60 const options = this.octokit.apps.listInstallationReposForAuthenticatedUser.endpoint.merge(61 { installation_id: installation.githubId },62 )63 const githubRepositories = await this.octokit.paginate(options)64 const { repositories, organizations } = await this.synchronizeRepositories(65 githubRepositories,66 )67 await this.synchronizeInstallationRepositoryRights(68 repositories,69 installation.id,70 )71 return { repositories, organizations }72 }73 async synchronizeRepositories(githubRepositories) {74 const [75 {76 owners: organizations,77 ownerIdByRepositoryId: organizationIdByRepositoryId,78 },79 { ownerIdByRepositoryId: userIdByRepositoryId },80 ] = await Promise.all([81 this.synchronizeOwners(githubRepositories, OWNER_ORGANIZATION),82 this.synchronizeOwners(githubRepositories, OWNER_USER),83 ])84 const repositories = await Promise.all(85 githubRepositories.map(async githubRepository => {86 const data = {87 githubId: githubRepository.id,88 name: githubRepository.name,89 organizationId: organizationIdByRepositoryId[githubRepository.id],90 userId: userIdByRepositoryId[githubRepository.id],91 private: githubRepository.private,92 }93 let [repository] = await Repository.query().where({94 githubId: githubRepository.id,95 })96 if (githubRepository.archived) {97 data.archived = true98 }99 if (repository) {100 await repository.$query().patchAndFetch(data)101 } else {102 repository = await Repository.query().insert({103 ...data,104 baselineBranch: githubRepository.default_branch,105 config: {106 files: [{ test: '*.js', maxSize: '10 mB' }],107 },108 })109 }110 return repository111 }),112 )113 return { repositories, organizations }114 }115 async synchronizeOwners(githubRepositories, type) {116 const githubOwners = githubRepositories.reduce(117 (githubOwners, githubRepository) => {118 if (githubRepository.owner.type !== type) {119 return githubOwners120 }121 let githubOwner = githubOwners.find(122 ({ id }) => id === githubRepository.owner.id,123 )124 if (!githubOwner) {125 githubOwner = githubRepository.owner126 githubOwners.push(githubRepository.owner)127 }128 return githubOwners129 },130 [],131 )132 let owners133 switch (type) {134 case OWNER_ORGANIZATION:135 owners = await Promise.all(136 githubOwners.map(githubOwner =>137 this.synchronizeOrganization(githubOwner),138 ),139 )140 break141 case OWNER_USER:142 owners = await Promise.all(143 githubOwners.map(githubOwner => this.synchronizeUser(githubOwner)),144 )145 break146 default:147 throw new Error(`Unsupported type ${type}`)148 }149 return {150 owners,151 ownerIdByRepositoryId: githubRepositories.reduce(152 (ownerIdByRepositoryId, githubRepository) => {153 if (githubRepository.owner.type === type) {154 ownerIdByRepositoryId[githubRepository.id] = owners.find(155 owner => owner.githubId === githubRepository.owner.id,156 ).id157 }158 return ownerIdByRepositoryId159 },160 {},161 ),162 }163 }164 // eslint-disable-next-line class-methods-use-this165 async synchronizeOrganization(githubOrganization) {166 const organizationData = await this.octokit.orgs.get({167 org: githubOrganization.login,168 })169 githubOrganization = organizationData.data170 let [organization] = await Organization.query().where({171 githubId: githubOrganization.id,172 })173 const data = {174 githubId: githubOrganization.id,175 name: githubOrganization.name,176 login: githubOrganization.login,177 }178 if (organization) {179 await organization.$query().patchAndFetch(data)180 } else {181 organization = await Organization.query().insert(data)182 }183 return organization184 }185 // eslint-disable-next-line class-methods-use-this186 async synchronizeUser(githubUser) {187 const data = { githubId: githubUser.id, login: githubUser.login }188 let user = await User.query()189 .where({ githubId: githubUser.id })190 .first()191 if (user) {192 await user.$query().patchAndFetch(data)193 } else {194 user = await User.query().insert(data)195 }196 return user197 }198 async synchronizeInstallationRepositoryRights(repositories, installationId) {199 const installationRepositoryRights = await InstallationRepositoryRight.query().where(200 {201 installationId,202 },203 )204 await Promise.all(205 repositories.map(async repository => {206 const hasRights = installationRepositoryRights.some(207 ({ repositoryId }) => repositoryId === repository.id,208 )209 if (!hasRights) {210 await InstallationRepositoryRight.query().insert({211 installationId,212 repositoryId: repository.id,213 })214 }215 }),216 )217 await Promise.all(218 installationRepositoryRights.map(async installationRepositoryRight => {219 const repositoryStillExists = repositories.find(220 ({ id }) => id === installationRepositoryRight.repositoryId,221 )222 if (!repositoryStillExists) {223 await installationRepositoryRight.$query().delete()224 }225 }),226 )227 }228 async synchronizeRepositoryRights(repositories, userId) {229 const userRepositoryRights = await UserRepositoryRight.query().where({230 userId,231 })232 await Promise.all(233 repositories.map(async repository => {234 const hasRights = userRepositoryRights.some(235 ({ repositoryId }) => repositoryId === repository.id,236 )237 if (!hasRights) {238 await UserRepositoryRight.query().insert({239 userId,240 repositoryId: repository.id,241 })242 }243 }),244 )245 await Promise.all(246 userRepositoryRights.map(async userRepositoryRight => {247 const repositoryStillExists = repositories.find(248 ({ id }) => id === userRepositoryRight.repositoryId,249 )250 if (!repositoryStillExists) {251 await userRepositoryRight.$query().delete()252 }253 }),254 )255 }256 async synchronizeOrganizationRights(organizations, userId) {257 const userOrganizationRights = await UserOrganizationRight.query().where({258 userId,259 })260 await Promise.all(261 organizations.map(async organization => {262 const hasRights = userOrganizationRights.some(263 ({ organizationId }) => organizationId === organization.id,264 )265 if (!hasRights) {266 await UserOrganizationRight.query().insert({267 userId,268 organizationId: organization.id,269 })270 }271 }),272 )273 await Promise.all(274 userOrganizationRights.map(async userOrganizationRight => {275 const organizationStillExists = organizations.find(276 ({ id }) => id === userOrganizationRight.organizationId,277 )278 if (!organizationStillExists) {279 await userOrganizationRight.$query().delete()280 }281 }),282 )283 }284 async synchronizeUserInstallations() {285 const options = this.octokit.apps.listInstallationsForAuthenticatedUser286 .endpoint.DEFAULTS287 const githubInstallations = await this.octokit.paginate(options)288 return Promise.all(289 githubInstallations.map(async githubInstallation => {290 return getOrCreateInstallation({291 githubId: githubInstallation.id,292 deleted: false,293 })294 }),295 )296 }297 async synchronizeUserInstallationRights(installations, userId) {298 const userInstallationRights = await UserInstallationRight.query().where({299 userId,300 })301 await Promise.all(302 installations.map(async installation => {303 const exists = userInstallationRights.some(304 ({ installationId }) => installationId === installation.id,305 )306 if (!exists) {307 await UserInstallationRight.query().insertAndFetch({308 userId,309 installationId: installation.id,310 })311 }312 }),313 )314 await Promise.all(315 userInstallationRights.map(async userInstallationRight => {316 const installationStillExists = installations.find(317 ({ id }) => id === userInstallationRight.installationId,318 )319 if (!installationStillExists) {320 await userInstallationRight.$query().delete()321 }322 }),323 )324 return installations325 }326 async synchronize() {327 this.synchronization = await this.synchronization.$query()328 switch (this.synchronization.type) {329 case 'installation':330 return this.synchronizeFromInstallation(331 this.synchronization.installationId,332 )333 case 'user':334 return this.synchronizeFromUser(this.synchronization.userId)335 default:336 throw new Error(337 `Unknown synchronization type "${this.synchronization.type}"`,338 )339 }340 }341 async synchronizeFromInstallation(installationId) {342 const installation = await Installation.query()343 .findById(installationId)344 .eager('users')345 if (installation.deleted) {346 await Promise.all(347 installation.users.map(async user => this.synchronizeFromUser(user.id)),348 )349 await this.synchronizeInstallationRepositoryRights([], installationId)350 return351 }352 this.octokit = getInstallationOctokit(installation)353 await this.synchronizeAppRepositories(installationId)354 await Promise.all(355 installation.users.map(async user => this.synchronizeFromUser(user.id)),356 )357 }358 async synchronizeFromUser(userId) {359 const user = await User.query().findById(userId)360 const tokenValid = await checkAccessTokenValidity(user.accessToken)361 if (!tokenValid) {362 await this.synchronizeUserInstallationRights([], userId)363 await Promise.all([364 this.synchronizeRepositoryRights([], userId),365 this.synchronizeOrganizationRights([], userId),366 ])367 return368 }369 this.octokit = getUserOctokit(user)370 const installations = await this.synchronizeUserInstallations(userId)371 await this.synchronizeUserInstallationRights(installations, userId)372 const results = await Promise.all(373 installations.map(installation =>374 this.synchronizeUserInstallationRepositories(installation),375 ),376 )377 const { repositories, organizations } = results.reduce(378 (all, result) => {379 all.repositories = [...all.repositories, ...result.repositories]380 all.organizations = [...all.organizations, ...result.organizations]381 return all382 },383 { repositories: [], organizations: [] },384 )385 await Promise.all([386 this.synchronizeRepositoryRights(repositories, userId),387 this.synchronizeOrganizationRights(organizations, userId),388 ])389 }...
Repository.js
Source:Repository.js
1import crypto from 'crypto'2import { promisify } from 'util'3import { BaseModel, mergeSchemas } from './util'4import { UserRepositoryRight } from './UserRepositoryRight'5import { User } from './User'6const generateRandomBytes = promisify(crypto.randomBytes)7export class Repository extends BaseModel {8 static tableName = 'repositories'9 static jsonSchema = mergeSchemas(BaseModel.jsonSchema, {10 required: ['githubId', 'name', 'private', 'config'],11 properties: {12 githubId: { type: 'number' },13 name: { type: 'string' },14 active: { type: 'boolean' },15 archived: { type: 'boolean' },16 token: { type: 'string' },17 organizationId: { type: ['string', null] },18 userId: { type: ['string', null] },19 private: { type: 'boolean' },20 baselineBranch: { type: 'string' },21 config: { type: 'object' },22 },23 })24 static relationMappings = {25 builds: {26 relation: BaseModel.HasManyRelation,27 modelClass: 'Build',28 join: {29 from: 'repositories.id',30 to: 'builds.repositoryId',31 },32 modify(builder) {33 return builder.orderBy('number', 'desc')34 },35 },36 installations: {37 relation: BaseModel.ManyToManyRelation,38 modelClass: 'Installation',39 join: {40 from: 'repositories.id',41 through: {42 from: 'installation_repository_rights.repositoryId',43 to: 'installation_repository_rights.installationId',44 },45 to: 'installations.id',46 },47 modify(builder) {48 return builder.where({ deleted: false })49 },50 },51 organization: {52 relation: BaseModel.BelongsToOneRelation,53 modelClass: 'Organization',54 join: {55 from: 'repositories.organizationId',56 to: 'organizations.id',57 },58 },59 user: {60 relation: BaseModel.BelongsToOneRelation,61 modelClass: 'User',62 join: {63 from: 'repositories.userId',64 to: 'users.id',65 },66 },67 }68 getUsers() {69 return this.constructor.getUsers(this.id)70 }71 async $beforeInsert(queryContext) {72 await super.$beforeInsert(queryContext)73 this.token = await Repository.generateToken()74 }75 async $relatedOwner() {76 if (this.userId) {77 if (!this.user) {78 this.user = await this.$relatedQuery('user')79 }80 return this.user81 }82 if (this.organizationId) {83 if (!this.organization) {84 this.organization = await this.$relatedQuery('organization')85 }86 return this.organization87 }88 return null89 }90 static getUsers(repositoryId) {91 return User.query()92 .select('users.*')93 .join(94 'user_repository_rights',95 'users.id',96 '=',97 'user_repository_rights.userId',98 )99 .join(100 'repositories',101 'user_repository_rights.repositoryId',102 '=',103 'repositories.id',104 )105 .where('repositories.id', repositoryId)106 }107 async $checkWritePermission(user) {108 return Repository.checkWritePermission(this, user)109 }110 async $checkReadPermission(user) {111 return Repository.checkReadPermission(this, user)112 }113 static async checkWritePermission(repository, user) {114 if (!user) return false115 const userRepositoryRight = await UserRepositoryRight.query()116 .where({ userId: user.id, repositoryId: repository.id })117 .first()118 return Boolean(userRepositoryRight)119 }120 static async checkReadPermission(repository, user) {121 if (!repository.private) return true122 return Repository.checkWritePermission(repository, user)123 }124 static async generateToken() {125 const token = await generateRandomBytes(20)126 return token.toString('hex')127 }...
Using AI Code Generation
1require(['argos/Models/User/UserRepositoryRight'], function (UserRepositoryRight) {2 var userRight = new UserRepositoryRight();3 userRight.getAccessRights('ADMIN').then(function (result) {4 console.log(result);5 });6});7require(['argos/Models/User/UserRepositoryRight'], function (UserRepositoryRight) {8 var userRight = new UserRepositoryRight();9 userRight.getAccessRights('ADMIN').then(function (result) {10 console.log(result);11 });12});13require(['argos/Models/User/UserRepositoryRight'], function (UserRepositoryRight) {14 var userRight = new UserRepositoryRight();15 userRight.getAccessRights('ADMIN').then(function (result) {16 console.log(result);17 });18});19require(['argos/Models/User/UserRepositoryRight'], function (UserRepositoryRight) {20 var userRight = new UserRepositoryRight();21 userRight.getAccessRights('ADMIN').then(function (result) {22 console.log(result);23 });24});25require(['argos/Models/User/UserRepositoryRight'], function (UserRepositoryRight) {26 var userRight = new UserRepositoryRight();27 userRight.getAccessRights('ADMIN').then(function (result) {28 console.log(result);29 });30});31require(['argos/Models/User/UserRepositoryRight'], function (UserRepositoryRight) {32 var userRight = new UserRepositoryRight();33 userRight.getAccessRights('ADMIN').then(function (result) {34 console.log(result);35 });36});37require(['argos/Models/User/UserRepositoryRight'], function (UserRepositoryRight) {38 var userRight = new UserRepositoryRight();39 userRight.getAccessRights('ADMIN').then(function (result) {40 console.log(result);41 });42});
Using AI Code Generation
1require(["argos-saleslogix/UserRepositoryRight"], function(UserRepositoryRight) {2 UserRepositoryRight.hasRight('someRightID').then(function(result) {3 });4});5require(["argos/App"], function(App) {6 App.contextService.hasContext('someContextID').then(function(result) {7 });8});9require(["argos/App"], function(App) {10 App.contextService.hasContext('someContextID').then(function(result) {11 });12});13require(["argos/App"], function(App) {14 App.contextService.hasContext('someContextID').then(function(result) {15 });16});17require(["argos/App"], function(App) {18 App.contextService.hasContext('someContextID').then(function(result) {19 });20});21require(["argos/App"], function(App) {22 App.contextService.hasContext('someContextID').then(function(result) {23 });24});25require(["argos/App"], function(App) {26 App.contextService.hasContext('someContextID').then(function(result) {27 });28});29require(["argos/App"],
Using AI Code Generation
1var userRepo = require('argos-sdk/src/UserRepository');2userRepo.right('testRight', function() {3 console.log('testRight passed');4});5var userRepo2 = require('argos-sdk/src/UserRepository');6userRepo2.right('testRight2', function() {7 console.log('testRight2 passed');8});9var userRepo = require('argos-sdk/src/UserRepository');10userRepo.right('testRight', function() {11 console.log('testRight passed');12});13var userRepo2 = require('argos-sdk/src/UserRepository');14userRepo2.right('testRight2', function() {15 console.log('testRight2 passed');16});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!