Skip to content

Commit

Permalink
style: prettier formatting (openwallet-foundation#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
auer-martin authored Mar 10, 2023
1 parent b6c55b2 commit b7b1641
Show file tree
Hide file tree
Showing 13 changed files with 865 additions and 893 deletions.
2 changes: 1 addition & 1 deletion .github/actions/deploy/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ inputs:
envs:
description: Which environment variables to pass to the deployment
required: false
default: ""
default: ''
private-key:
description: private key used for ssh'ing into the server
required: true
Expand Down
5 changes: 5 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"printWidth": 120,
"semi": false,
"singleQuote": true
}
25 changes: 10 additions & 15 deletions jest.config.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,21 @@
import type { Config } from "@jest/types";
import type { Config } from '@jest/types'

import packageJson from "./package.json";
import packageJson from './package.json'

const config: Config.InitialOptions = {
displayName: packageJson.name,
testTimeout: 120000,
preset: "ts-jest",
testEnvironment: "node",
coveragePathIgnorePatterns: [
"/build/",
"/node_modules/",
"/__tests__/",
"tests",
],
coverageDirectory: "<rootDir>/coverage/",
preset: 'ts-jest',
testEnvironment: 'node',
coveragePathIgnorePatterns: ['/build/', '/node_modules/', '/__tests__/', 'tests'],
coverageDirectory: '<rootDir>/coverage/',
verbose: true,
testMatch: ["**/?(*.)+(spec|test).[tj]s?(x)"],
testMatch: ['**/?(*.)+(spec|test).[tj]s?(x)'],
globals: {
"ts-jest": {
'ts-jest': {
isolatedModules: true,
},
},
};
}

export default config;
export default config
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
"test": "jest",
"build": "yarn run clean && yarn run compile",
"clean": "rimraf -rf ./build",
"prettier": "prettier --ignore-path .gitignore '**/*.+(js|json|ts|md|yml|yaml|mdx)'",
"format": "yarn prettier --write",
"check-format": "yarn prettier --list-different",
"compile": "tsc -p tsconfig.build.json",
"prepublishOnly": "yarn run build",
"dev": "ts-node dev",
Expand All @@ -40,6 +43,7 @@
"@aries-framework/node": "^0.4.0-alpha.66",
"express": "^4.18.1",
"indy-sdk": "^1.16.0-dev-1655",
"prettier": "^2.8.4",
"tslog": "^3.3.3",
"tsyringe": "^4.7.0",
"ws": "^8.8.1"
Expand Down
118 changes: 53 additions & 65 deletions src/agent.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,22 @@
import {
InitConfig,
OutOfBandRole,
OutOfBandState,
} from "@aries-framework/core";
import type { Socket } from "net";
import {
HttpOutboundTransport,
Agent,
WsOutboundTransport,
} from "@aries-framework/core";
import { InitConfig, OutOfBandRole, OutOfBandState } from '@aries-framework/core'
import type { Socket } from 'net'
import { HttpOutboundTransport, Agent, WsOutboundTransport } from '@aries-framework/core'

import {
HttpInboundTransport,
agentDependencies,
WsInboundTransport,
IndySdkPostgresWalletScheme,
loadIndySdkPostgresPlugin,
} from "@aries-framework/node";
} from '@aries-framework/node'

import indySdk, { setDefaultLogger } from "indy-sdk";
import indySdk, { setDefaultLogger } from 'indy-sdk'

import express from "express";
import { writeFileSync } from "fs";
import { tmpdir } from "os";
import path from "path";
import { Server } from "ws";
import express from 'express'
import { writeFileSync } from 'fs'
import { tmpdir } from 'os'
import path from 'path'
import { Server } from 'ws'

import {
AGENT_ENDPOINTS,
Expand All @@ -42,28 +34,28 @@ import {
POSTGRES_USER,
WALLET_KEY,
WALLET_NAME,
} from "./constants";
import { Logger } from "./logger";
import { StorageMessageQueueModule } from "./storage/StorageMessageQueueModule";
import { IndySdkModule } from "@aries-framework/indy-sdk";
} from './constants'
import { Logger } from './logger'
import { StorageMessageQueueModule } from './storage/StorageMessageQueueModule'
import { IndySdkModule } from '@aries-framework/indy-sdk'

if (DEBUG_INDY) {
setDefaultLogger("trace");
setDefaultLogger('trace')
}

export async function createAgent() {
// We create our own instance of express here. This is not required
// but allows use to use the same server (and port) for both WebSockets and HTTP
const app = express();
const socketServer = new Server({ noServer: true });
const app = express()
const socketServer = new Server({ noServer: true })

const logger = new Logger(LOG_LEVEL);
const logger = new Logger(LOG_LEVEL)

// Only load postgres database in production
const storageConfig = IS_DEV ? undefined : loadPostgres();
const storageConfig = IS_DEV ? undefined : loadPostgres()

if (storageConfig) {
logger.info("Using postgres storage");
logger.info('Using postgres storage')
}

const agentConfig: InitConfig = {
Expand All @@ -78,7 +70,7 @@ export async function createAgent() {
autoAcceptMediationRequests: true,
autoUpdateStorageOnStartup: true,
logger,
};
}

// Set up agent
const agent = new Agent({
Expand All @@ -90,54 +82,52 @@ export async function createAgent() {
indySdk,
}),
},
});
})

// Create all transports
const httpInboundTransport = new HttpInboundTransport({
app,
port: AGENT_PORT,
});
const httpOutboundTransport = new HttpOutboundTransport();
const wsInboundTransport = new WsInboundTransport({ server: socketServer });
const wsOutboundTransport = new WsOutboundTransport();
})
const httpOutboundTransport = new HttpOutboundTransport()
const wsInboundTransport = new WsInboundTransport({ server: socketServer })
const wsOutboundTransport = new WsOutboundTransport()

// Register all Transports
agent.registerInboundTransport(httpInboundTransport);
agent.registerOutboundTransport(httpOutboundTransport);
agent.registerInboundTransport(wsInboundTransport);
agent.registerOutboundTransport(wsOutboundTransport);
agent.registerInboundTransport(httpInboundTransport)
agent.registerOutboundTransport(httpOutboundTransport)
agent.registerInboundTransport(wsInboundTransport)
agent.registerOutboundTransport(wsOutboundTransport)

// eslint-disable-next-line @typescript-eslint/no-misused-promises
httpInboundTransport.app.get("/invite", async (req, res) => {
if (!req.query._oobid || typeof req.query._oobid !== "string") {
return res.status(400).send("Missing or invalid _oobid");
httpInboundTransport.app.get('/invite', async (req, res) => {
if (!req.query._oobid || typeof req.query._oobid !== 'string') {
return res.status(400).send('Missing or invalid _oobid')
}

const outOfBandRecord = await agent.oob.findById(req.query._oobid);
const outOfBandRecord = await agent.oob.findById(req.query._oobid)

if (
!outOfBandRecord ||
outOfBandRecord.role !== OutOfBandRole.Sender ||
outOfBandRecord.state !== OutOfBandState.AwaitResponse
) {
return res
.status(400)
.send(`No invitation found for _oobid ${req.query._oobid}`);
return res.status(400).send(`No invitation found for _oobid ${req.query._oobid}`)
}
return res.send(outOfBandRecord.outOfBandInvitation.toJSON());
});
return res.send(outOfBandRecord.outOfBandInvitation.toJSON())
})

await agent.initialize();
await agent.initialize()

// When an 'upgrade' to WS is made on our http server, we forward the
// request to the WS server
httpInboundTransport.server?.on("upgrade", (request, socket, head) => {
httpInboundTransport.server?.on('upgrade', (request, socket, head) => {
socketServer.handleUpgrade(request, socket as Socket, head, (socket) => {
socketServer.emit("connection", socket, request);
});
});
socketServer.emit('connection', socket, request)
})
})

return agent;
return agent
}

function loadPostgres() {
Expand All @@ -148,38 +138,36 @@ function loadPostgres() {
!POSTGRES_ADMIN_USER ||
!POSTGRES_ADMIN_PASSWORD
) {
throw new Error("Missing required postgres environment variables");
throw new Error('Missing required postgres environment variables')
}

let postgresTlsFile = POSTGRES_TLS_CA_FILE;
let postgresTlsFile = POSTGRES_TLS_CA_FILE
if (!postgresTlsFile && POSTGRES_TLS_CA) {
postgresTlsFile = path.join(tmpdir(), "postgres-tls.crt");
writeFileSync(postgresTlsFile, POSTGRES_TLS_CA);
postgresTlsFile = path.join(tmpdir(), 'postgres-tls.crt')
writeFileSync(postgresTlsFile, POSTGRES_TLS_CA)
}

if (!postgresTlsFile) {
throw new Error(
"Missing required POSTGRES_TLS_CA_FILE or POSTGRES_TLS_CA environment variable"
);
throw new Error('Missing required POSTGRES_TLS_CA_FILE or POSTGRES_TLS_CA environment variable')
}

const storageConfig = {
type: "postgres_storage",
type: 'postgres_storage',
config: {
url: POSTGRES_DATABASE_URL,
wallet_scheme: IndySdkPostgresWalletScheme.DatabasePerWallet,
tls_ca: postgresTlsFile,
tls: "Require",
tls: 'Require',
},
credentials: {
account: POSTGRES_USER,
password: POSTGRES_PASSWORD,
admin_account: POSTGRES_ADMIN_USER,
admin_password: POSTGRES_ADMIN_PASSWORD,
},
};
}

loadIndySdkPostgresPlugin(storageConfig.config, storageConfig.credentials);
loadIndySdkPostgresPlugin(storageConfig.config, storageConfig.credentials)

return storageConfig;
return storageConfig
}
38 changes: 18 additions & 20 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,25 @@
import { LogLevel } from "@aries-framework/core";
import { LogLevel } from '@aries-framework/core'

export const AGENT_PORT = process.env.AGENT_PORT
? Number(process.env.AGENT_PORT)
: 3000;
export const AGENT_NAME = process.env.AGENT_NAME || "Animo Mediator";
export const WALLET_NAME = process.env.WALLET_NAME || "animo-mediator-dev";
export const WALLET_KEY = process.env.WALLET_KEY || "animo-mediator-dev";
export const AGENT_ENDPOINTS = process.env.AGENT_ENDPOINTS?.split(",") ?? [
export const AGENT_PORT = process.env.AGENT_PORT ? Number(process.env.AGENT_PORT) : 3000
export const AGENT_NAME = process.env.AGENT_NAME || 'Animo Mediator'
export const WALLET_NAME = process.env.WALLET_NAME || 'animo-mediator-dev'
export const WALLET_KEY = process.env.WALLET_KEY || 'animo-mediator-dev'
export const AGENT_ENDPOINTS = process.env.AGENT_ENDPOINTS?.split(',') ?? [
`http://localhost:${AGENT_PORT}`,
`ws://localhost:${AGENT_PORT}`,
];
]

export const POSTGRES_DATABASE_URL = process.env.POSTGRES_DATABASE_URL;
export const POSTGRES_USER = process.env.POSTGRES_USER;
export const POSTGRES_PASSWORD = process.env.POSTGRES_PASSWORD;
export const POSTGRES_ADMIN_USER = process.env.POSTGRES_ADMIN_USER;
export const POSTGRES_ADMIN_PASSWORD = process.env.POSTGRES_ADMIN_PASSWORD;
export const POSTGRES_TLS_CA_FILE = process.env.POSTGRES_TLS_CA_FILE;
export const POSTGRES_TLS_CA = process.env.POSTGRES_TLS_CA;
export const POSTGRES_DATABASE_URL = process.env.POSTGRES_DATABASE_URL
export const POSTGRES_USER = process.env.POSTGRES_USER
export const POSTGRES_PASSWORD = process.env.POSTGRES_PASSWORD
export const POSTGRES_ADMIN_USER = process.env.POSTGRES_ADMIN_USER
export const POSTGRES_ADMIN_PASSWORD = process.env.POSTGRES_ADMIN_PASSWORD
export const POSTGRES_TLS_CA_FILE = process.env.POSTGRES_TLS_CA_FILE
export const POSTGRES_TLS_CA = process.env.POSTGRES_TLS_CA

export const INVITATION_URL = process.env.INVITATION_URL;
export const INVITATION_URL = process.env.INVITATION_URL

export const LOG_LEVEL = LogLevel.debug;
export const LOG_LEVEL = LogLevel.debug

export const IS_DEV = process.env.NODE_ENV === "development";
export const DEBUG_INDY = process.env.DEBUG_INDY === "true";
export const IS_DEV = process.env.NODE_ENV === 'development'
export const DEBUG_INDY = process.env.DEBUG_INDY === 'true'
36 changes: 13 additions & 23 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,32 @@
import {
OutOfBandRepository,
OutOfBandRole,
OutOfBandState,
} from "@aries-framework/core";
import { OutOfBandRepository, OutOfBandRole, OutOfBandState } from '@aries-framework/core'

import { createAgent } from "./agent";
import { INVITATION_URL } from "./constants";
import { createAgent } from './agent'
import { INVITATION_URL } from './constants'

void createAgent().then(async (agent) => {
agent.config.logger.info("Agent started");
agent.config.logger.info('Agent started')

// Try to find existing out of band record
const oobRepo = agent.dependencyManager.resolve(OutOfBandRepository);
const oobRepo = agent.dependencyManager.resolve(OutOfBandRepository)
const outOfBandRecords = await oobRepo.findByQuery(agent.context, {
state: OutOfBandState.AwaitResponse,
role: OutOfBandRole.Sender,
});
})

let outOfBandRecord = outOfBandRecords.find(
(oobRecord) => oobRecord.reusable
);
let outOfBandRecord = outOfBandRecords.find((oobRecord) => oobRecord.reusable)

// If it does't exist, we create a new one
if (!outOfBandRecord) {
outOfBandRecord = await agent.oob.createInvitation({
multiUseInvitation: true,
});
})
}

const httpEndpoint = agent.config.endpoints.find((e) =>
e.startsWith("http")
) as string;
const invitationEndpoint = INVITATION_URL ?? `${httpEndpoint}/invite`;
const httpEndpoint = agent.config.endpoints.find((e) => e.startsWith('http')) as string
const invitationEndpoint = INVITATION_URL ?? `${httpEndpoint}/invite`
const mediatorInvitationUrlLong = outOfBandRecord.outOfBandInvitation.toUrl({
domain: invitationEndpoint,
});
})

agent.config.logger.info(
`Out of band invitation url: \n\n\t${mediatorInvitationUrlLong}`
);
});
agent.config.logger.info(`Out of band invitation url: \n\n\t${mediatorInvitationUrlLong}`)
})
Loading

0 comments on commit b7b1641

Please sign in to comment.