repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
skimah/skimah
packages/ds-csv/src/csv.ts
import JSONRecords from "@skimah/ds-json"; import { csvParse } from "d3-dsv"; export interface Config { /** * The path of the csv file that should be loaded */ filepath?: string; /** * CSV text that should be used in lieu of a file */ records?: string; } export default class CSVRecords extends JSONRecords { constructor(private csvConfig: Config) { super(Object.assign({}, csvConfig, { records: null })); } private loadCSV() { const { readFileSync } = require("fs"); const csvText = readFileSync(this.csvConfig.filepath).toString(); return csvParse(csvText); } async initialize() { if (this.csvConfig.filepath) { this.records = this.loadCSV(); } if (this.csvConfig.records) { this.records = csvParse(this.csvConfig.records); } } }
skimah/skimah
packages/ds-faker/test/faker.test.ts
import { generate, SkimahConfig } from "@skimah/api"; import { graphql } from "graphql"; import SampleSource from "../src/faker"; const typeDefs = ` type Manager @datasource(name: "sample") { id: ID firstName: String @named(as: "FirstName_name_firstName") lastName: String @named(as: "LastName_name_lastName") title: String @named(as: "Title_name_jobTitle") status:Boolean @named(as:"userStatus") events: [Event] @relation } type Event @datasource(name: "sample") { eventId: ID date: String @named(as: "eventData_date_recent") managedBy: Manager @relation } `; let schema; describe("Datasource SampleData", () => { beforeAll(async () => { const sample = new SampleSource({ recordMaximum: 10 }); const config: SkimahConfig = { typeDefs, sources: { sample } }; const skimahResult = await generate(config); schema = skimahResult.schema; }); describe("Selection", () => { test("Skip and Limit", async () => { const query = ` query { findManagers(limit: 2) { id firstName lastName title } } `; const result = await graphql(schema, query); expect(result.errors).toBeUndefined(); const [first] = <any[]>result.data.findManagers; expect(first.id).not.toBeNull(); expect(first.firstName).not.toBeNull(); expect(first.lastName).not.toBeNull(); expect(first.title).not.toBeNull(); }); test("One-to-Many Relationships", async () => { const query = ` query { findManagers(limit: 2) { id firstName events { date } } } `; const result = await graphql(schema, query); expect(result.errors).toBeUndefined(); const [first] = <any[]>result.data.findManagers; expect(first.events[0].id).not.toBeNull(); expect(first.events[0].date).not.toBeNull(); }); test("One-to-One Relationships", async () => { const query = ` query { findEvents(limit: 2) { eventId managedBy { firstName } } } `; const result = await graphql(schema, query); expect(result.errors).toBeUndefined(); const [first] = <any[]>result.data.findEvents; expect(first.managedBy.firstName).not.toBeNull(); }); }); describe("Mutations", () => { test("Creation", async () => { const query = ` mutation { createManagers( data: [ { id:100, firstName: "Bobby", lastName: "Jose", title: "Regional Manager" }, { id:200, firstName: "Jose", lastName: "Murihino", title: "Branch Manager" } ] ) { affected managers { title } } } `; const result = await graphql(schema, query); expect(result.errors).toBeUndefined(); expect(result.data).toMatchInlineSnapshot(` Object { "createManagers": Object { "affected": Array [ "100", "200", ], "managers": Array [ Object { "title": "Regional Manager", }, Object { "title": "Branch Manager", }, ], }, } `); }); test("Update", async () => { const query = ` mutation { updateManagers( changes: { title: "National Manager" }, where: { firstName: { eq: "Jose" } } ) { affected managers { id firstName lastName title } } } `; const result = await graphql(schema, query); expect(result.errors).toBeUndefined(); expect(result.data).toMatchInlineSnapshot(` Object { "updateManagers": Object { "affected": Array [ "200", ], "managers": Array [ Object { "firstName": "Jose", "id": "200", "lastName": "Murihino", "title": "National Manager", }, ], }, } `); }); test("Delete", async () => { const query = ` mutation { deleteManagers( where: { firstName: { eq: "Jose" } } ) { affected managers { title } } } `; const result = await graphql(schema, query); expect(result.errors).toBeUndefined(); expect(result.data).toMatchInlineSnapshot(` Object { "deleteManagers": Object { "affected": Array [ "200", ], "managers": Array [ Object { "title": "National Manager", }, ], }, } `); }); }); describe("Malformed", () => { test("Malformed attributes directives", async () => { const badTypeDef = ` type Agent @datasource(name:"sample") { id: ID @named(as: "random_number") name: String @named(as: "bad_directive") } `; const sample = new SampleSource({ recordMaximum: 10 }); const config: SkimahConfig = { typeDefs: badTypeDef, sources: { sample } }; return expect(generate(config)).rejects.toContain( `The attribute named \"bad_directive\" does not match the format` ); }); }); });
skimah/skimah
packages/ds-faker/src/faker.ts
import { Attribute, Datasource, Model, MutationModel, MutationResponse, QueryModel, Criteria } from "@skimah/api"; import JSONRecords from "@skimah/ds-json"; import faker from "faker"; export interface Config { /** * Maximum number of records to be generated for each type */ recordMaximum: number; } const rangeGen = (start, max: number): number => { return Math.round(start + Math.random() * max); }; const fakerGenerator = (source: string): any => { const errMsg = `The attribute named "${source}" does not match the format fakerNamespace_function e.g address_zipCode. see https://rawgit.com/Marak/faker.js/master/examples/browser/index.html`; try { const [ /** Source name */ param1, /** Faker namespace */ param2, /** Faker functions */ param3 ] = source.split("_"); // source_fakerNamespace_function if (param3) { return faker[param2][param3](); } // source_fakerNamespace_function if (param2) { return faker[param1][param2](); } } catch { throw new Error(errMsg); } }; const generateRecords = (config: Config, model: Model) => { const records = []; for (let index = 0; index < config.recordMaximum; index++) { const record = {}; Object.values(model.attributes).forEach((attr: Attribute) => { if (attr.unique) { // auto increment ID/@unique values record[attr.sourceName] = index + 1; } else { record[attr.sourceName] = fakerGenerator(attr.sourceName); } }); /** * For every one-to-one relationship, generate a foreign key * in the bounds of the max values of the parent * * All parents will not be guaranteed to have children */ Object.values(model.relations) .filter(relation => !relation.isCollection) .forEach(relation => { // auto generate foreign keys between 0 and config.max record[relation.sourceName] = index + 1; }); records.push(record); } return records; }; export default class SampleRecords implements Datasource { private records: { [key: string]: JSONRecords } = {}; constructor(private config: Config) {} async initialize(models: Model[]) { models.forEach(m => { const record = new JSONRecords({ records: generateRecords(this.config, m) }); record.initialize([m]); this.records[m.name] = record; }); } async create(models: MutationModel[]): Promise<MutationResponse<any>> { const [first] = models; if (first) { return this.records[models[0].name].create(models); } else { return { affected: [] }; } } async select(selection: QueryModel): Promise<any[]> { const parents = await this.records[selection.name].select(selection); for (const relation of Object.values(selection.projectedRelations)) { const originalCriteria = relation.model.criteria.and; for (const parent of parents) { const newCriteria = { [relation.condition.child.sourceName]: { eq: parent[relation.condition.parent.name] } }; // new criteria to be used to fetch child records relation.model.criteria.and = [...originalCriteria, newCriteria]; if (relation.isCollection) { const children = await this.select(relation.model); parent[relation.name] = children; } else { const [child] = await this.select(relation.model); parent[relation.name] = child; } } } return parents; } async update( criteria: Criteria, changes: MutationModel ): Promise<MutationResponse<any>> { return this.records[changes.name].update(criteria, changes); } async delete( criteria: Criteria, model: Model ): Promise<MutationResponse<any>> { return this.records[model.name].delete(criteria, model); } }
skimah/skimah
packages/api/src/types.ts
import { GraphQLResolveInfo, GraphQLSchema } from "graphql"; import { InterfaceTypeComposer, ObjectTypeComposer, SchemaComposer } from "graphql-compose"; /** * @internal */ export type AttributeType = "String" | "Float" | "Int" | "Boolean" | "ID"; /** * @internal */ export type GraphqlResolver = ( parent: any, args: any, context: any, info: GraphQLResolveInfo ) => Promise<any>; /** * A skimah model field. This is the graphql field defined in the type definition */ export interface Field { /** * The name of the field as defined in the schema definition of the type */ name: string; /** * The name of the field in the record in the underlying * datasource using the directive `@named`. This will * default to the field name if `@named` directive is not used */ sourceName: string; } /** * Model field attribute */ export interface Attribute extends Field { /** * The type of the attribute as defined in the schema */ type: AttributeType; /** * Defines if this field is unique. This can be defined in the schema field * with the `@unique` directive or any field of type `ID` */ unique: boolean; } /** * The condition attached to a relationship. */ export interface RelationCondition { /** * The field in the type referenced by the `@relation` directive on the parent field */ child: Field; /** * The field on which the `@relation` is defined in the parent type */ parent: Field; } /** * Represents a relationship between two types in the schema definition * * A relation is defined in the schema with the aid of a `@relation` directive * * e.g * * ```graphql * type User { * id: ID * comments: [Comments] `@relation` * } * * type Comment { * id: ID * user: `@relation` * } * * ``` * * The above schema will generate a one-to-many relationship from the `User` to the `Comment` * and a one-to-one relationship between a `Comment` and a `User` * */ export interface Relation extends Field { /** * Represents a one-to-many relationship. */ isCollection: boolean; /** * The child model of this relation */ model?: QueryModel; /** * The type of the model */ type: string; /** * The condition by which this relationship is created. */ condition?: RelationCondition; } /** * A Model maps directly to an Object type definition in a schema definition. */ export interface Model { /** * The name of the type from the schema definition */ name: string; /** * The datasource associated with this model. This is the datasource * that is defined in the schema using the `@datasource` directive. * * This will default to `default` if not specified, meaning all type * definition without a `@datasource` definition will use a default * datasource if defined */ // TODO: change to instance of datasource datasource: string; /** * The name of this model in the datasource */ sourceName: string; /** * Scalar fields detected from the type definition in the schema */ attributes: { [key: string]: Attribute }; /** * Unique identifiers for the type referenced by this model. * A model can have multiple identities. * Any field of type ID or a directive `@unique` will be considered an identity */ identities: Attribute[]; /** * The relationships defined in the schema. i.e non scalar fields */ relations: { [key: string]: Relation }; } export interface Resolvers { Query?: { [key: string]: GraphqlResolver; }; Mutation?: { [key: string]: GraphqlResolver; }; } /** * A model filter criteria. This is directly generated from the input * fields to a graphql query operation. The criteria is modelled after * mongodb query operators. * * An example criteria looks like * * { * name: { eq: "Bond" } * } * * @see https://docs.mongodb.com/manual/reference/operator/query-comparison/ */ export interface CriteriaFilter { /** * Matches values that are equal to a specified value. */ eq?: any; /** * Matches all values that are not equal to a specified value. */ ne?: any; /** * Matches values that are less than or equal to a specified value. */ lte?: any; /** * Matches values that are less than a specified value. */ lt?: any; /** * Matches values that are greater than or equal to a specified value. */ gte?: any; /** * Matches values that are greater than a specified value. */ gt?: any; /** * Matches values that are less than or equal to a specified value. */ like?: any; /** * Matches any of the values specified in an array. */ in?: any; /** * Matches none of the values specified in an array. */ nin?: any; } /** * Directive in which retrieved records should be sorted */ declare enum SortDirection { /** * Sort records in descending order */ desc = "desc", /** * Sort records in ascending order */ asc = "asc" } /** * The criteria that is supplied to a datasource implementation to fetch * the appropriate records from the underlying datasource. */ export interface Criteria { /** * A combination of criteria filters to be treated as an `and` operation */ and?: { [key: string]: CriteriaFilter }[]; /** * A combination of criteria filters to be treated as an `or` operation */ or?: { [key: string]: CriteriaFilter }[]; /** * Sort the results of the records */ orderBy?: { [key: string]: SortDirection }; /** * Limit the results of the records */ limit?: number; /** * Skip the number of records to return from the underlying datasource */ skip?: number; } /** * A model to be selected model containing information on how to be selected from the source * * The attributes and relations will contain the projection from the graphql * selection set. */ export interface QueryModel extends Model { /** * The criteria to be used for the selection of records from the underlying datasource */ criteria: Criteria; /** * The selection of attributes that have been explicitly selected * for querying the underlying datasource */ projectedAttributes: { [key: string]: Attribute }; /** * Nested relationship selections */ projectedRelations: { [key: string]: Relation }; } /** * A mutation */ export interface MutationAttribute extends Attribute { /** * The value attached to */ value: any; } /** * An extension of a skimah model used as arguments to datasource * operations that mutates underlying datasources. * */ export interface MutationModel extends Model { /** * Attributes that contains values to be mutated */ mutatedAttributes: { [key: string]: MutationAttribute }; } /** * Mutation Response */ export interface MutationResponse<T> { /** * The identity of the just mutated records. This is used if * the mutated records are requested in the same operation */ affected: any[]; /** * The records that have just been mutated. */ records?: T[]; } /** * A Skimah Datasource is an object with a CRUD (create, read, update and delete) interface * that will be called by resolvers when an associated model is queried or mutated. * * A Datasource is a generic interface to interact with an underlying datasource which could be * anything from a filesystem, database, cache or even another graphql system. * * A datasource can be reused multiple times across models defined in a schema. * */ export interface Datasource { /** * Called for once for every type in the type definition */ initialize?: (models: Model[]) => Promise<any>; /** * * Creates a collection of records in the underlying datasource when the mutation operation is * invoked by the graphql operation * * @param models The models to be created in the underlying datasource * @return The mutation response */ create: (models: MutationModel[]) => Promise<MutationResponse<any>>; /** * * Selects a collection of records from the datasource using the selection fields * from the graphql query and the criteria by which to apply to the selection operation * * @param selection The model that contains all the information needed to select * records from the underlying the datasource * * @returns An array of records from the underlying datasource mapped correctly using the * projected attributes in the query model */ select: (selection: QueryModel) => Promise<Array<any>>; /** * Updates underlying datasource records with the changes from a graphql mutation operation * * @param criteria The criteria by which the changes should be applied * @param changes A mutation model with values to be applied */ update: ( criteria: Criteria, changes: MutationModel ) => Promise<MutationResponse<any>>; /** * Deletes underlying datasource records * * @remarks * Delete is a special case, in that before the delete operation is executed, the resolver * will do a select using the same criteria before requesting the delete execution if records * are requested and only if records are requested. * * @param criteria The criteria by which to delete models from the underlying datasource. * @param model The model representing record definition in the underlying datasource. */ delete: (criteria: Criteria, model: Model) => Promise<MutationResponse<any>>; } export interface SkimahConfig { /** * The graphql type definitions to generate the skimah API from. Each defined type * in the schema will have an API generated for them. */ typeDefs: string; /** * A dictionary of datasources linked to Datasource instances. * * Datasources to source records from using the `@datasource` directive in * the schema definition * * e.g * * ```graphql * type User @datasource(name: "mysql-users") { * id: ID * email: String * } * ``` * */ sources: { [key: string]: Datasource }; } /** * The result of generating a Skimah API */ export interface SkimahResult { /** * An executable schema ready to used with a choice of graphql server. * The graphql schema has all the necessary resolvers attached and will * execute the appropriate datasources declared on the types */ schema: GraphQLSchema; /** * These are the resolvers automatically generated for the models in the schema */ resolvers: { [key: string]: any }; /** * These are the skimah generated models that can be useful for introspection and debugging */ models: { [key: string]: any }; /** * Schema composer, useful for debugging * * @see https://graphql-compose.github.io/ */ schemaComposer: SchemaComposer<any>; } export type DefinedType = | InterfaceTypeComposer<any, any> | ObjectTypeComposer<any, any> | InterfaceTypeComposer<any, any>; /** * Generate an API from schema */ export interface generate { /** * @param config Skimah configuration to modify the behavior * of the generated API */ (config: SkimahConfig): Promise<SkimahResult>; }
skimah/skimah
packages/api/test/resolvers/update.test.ts
<gh_stars>1-10 import generate from "../../src/generate"; import { Datasource } from "../../src/types"; import { graphql } from "graphql"; const typeDefs = ` type User { userid: ID age: Int height: Float avatar: Avatar @relation } type Avatar { id: ID url: String } `; describe("Schema Resolvers", () => { test("update criteria", async () => { const source: Datasource = { select: jest.fn(), update: jest.fn(), create: jest.fn(), delete: jest.fn() }; const { schema } = await generate({ typeDefs, sources: { default: source } }); const query = ` mutation { updateUsers ( where: { age:{ gte: 10 }, height: { lt: 50 } }, changes: { userid:2, age: 20, avatar: 2 }) { affected } } `; const result = await graphql(schema, query); expect(result.errors).toBeUndefined(); const [[arg, criteria]] = (source.update as jest.MockedFunction< any >).mock.calls; expect(source.update).toHaveBeenCalledTimes(1); expect(arg.mutatedAttributes).toMatchInlineSnapshot(`undefined`); expect(criteria).toMatchInlineSnapshot(` Object { "attributes": Object { "age": Object { "name": "age", "sourceName": "age", "type": "Int", "unique": false, }, "height": Object { "name": "height", "sourceName": "height", "type": "Float", "unique": false, }, "userid": Object { "name": "userid", "sourceName": "userid", "type": "ID", "unique": true, }, }, "datasource": "default", "identities": Array [ Object { "name": "userid", "sourceName": "userid", "type": "ID", "unique": true, }, ], "mutatedAttributes": Object { "age": Object { "name": "age", "sourceName": "age", "type": "Int", "unique": false, "value": 20, }, "avatar": Object { "name": "avatar", "sourceName": "avatar", "type": "ID", "unique": true, "value": "2", }, "userid": Object { "name": "userid", "sourceName": "userid", "type": "ID", "unique": true, "value": "2", }, }, "name": "User", "relations": Object { "avatar": Object { "condition": Object { "child": Object { "name": "id", "sourceName": "id", }, "parent": Object { "name": "avatar", "sourceName": "avatar", }, }, "isCollection": false, "model": null, "name": "avatar", "sourceName": "avatar", "type": "Avatar", "unique": false, }, }, "sourceName": "User", } `); }); test("updated records", async () => { const source: Datasource = { select: jest.fn(() => Promise.resolve([])), update: jest.fn(() => Promise.resolve({ affected: ["1", "2", "3"] }) ), create: jest.fn(), delete: jest.fn() }; const { schema } = await generate({ typeDefs, sources: { default: source } }); const query = ` mutation { updateUsers ( where: { age:{ gte: 10 }, height: { lt: 50 } }, changes: { userid:2, age: 20 }) { affected users { userid } } } `; const result = await graphql(schema, query); expect(result.errors).toBeUndefined(); const [[arg]] = (source.select as jest.MockedFunction<any>).mock.calls; expect(arg).toMatchInlineSnapshot(` Object { "attributes": Object { "age": Object { "name": "age", "sourceName": "age", "type": "Int", "unique": false, }, "height": Object { "name": "height", "sourceName": "height", "type": "Float", "unique": false, }, "userid": Object { "name": "userid", "sourceName": "userid", "type": "ID", "unique": true, }, }, "criteria": Object { "and": Array [ Object { "userid": Object { "in": Array [ "1", "2", "3", ], }, }, ], "limit": undefined, "or": Array [], "orderBy": Object {}, "skip": undefined, }, "datasource": "default", "identities": Array [ Object { "name": "userid", "sourceName": "userid", "type": "ID", "unique": true, }, ], "name": "User", "projectedAttributes": Object { "userid": Object { "name": "userid", "sourceName": "userid", "type": "ID", "unique": true, }, }, "projectedRelations": Object {}, "relations": Object { "avatar": Object { "condition": Object { "child": Object { "name": "id", "sourceName": "id", }, "parent": Object { "name": "avatar", "sourceName": "avatar", }, }, "isCollection": false, "model": null, "name": "avatar", "sourceName": "avatar", "type": "Avatar", "unique": false, }, }, "sourceName": "User", } `); }); });
skimah/skimah
packages/api/src/response.ts
import { getPluralName, ObjectTypeComposer, SchemaComposer } from "graphql-compose"; /** @internal */ export default (tc: ObjectTypeComposer, composer: SchemaComposer<any>) => { const typeName = tc.getTypeName(); const pluralNames = getPluralName(typeName); composer.getOrCreateOTC(`${typeName}MutationResponse`, rtc => { rtc.addFields({ affected: { type: `[ID!]!`, description: `The total number of ${pluralNames} affected` }, [pluralNames]: { type: tc .getTypeNonNull() .getTypePlural() .getTypeNonNull(), description: `The affected ${pluralNames}`, /** * The parent is a type of MutationResponse { affected, records } * */ resolve: async (parent, args, context, info) => { if (!parent) { return Promise.reject( `IDs must be returned from mutation datasource` ); } /** * If the records have returned already by the parent, resolver, * just respond with it. */ if (parent.records) { return parent.records; } /** * Use the find resolver on the type source * the model. include the affected records * in the find context */ const resolverName = getPluralName(`find${tc.getTypeName()}`); const resolver = tc.getResolver(resolverName); const response = await resolver.resolve({ args, info, source: null, context: Object.assign({}, context, { mutationAffected: parent.affected }) }); return response; } } }); }); };
skimah/skimah
packages/api/src/orderby.ts
/** * This will generate an input OrderBy with _OrderBy enum for each model type in the * type definition * * e.g * type User { * name: String * age: Float * } * * This model will generate * * UserOrderBy { * name: _OrderBy * age: _OrderBy * } */ import { InputTypeComposerFieldConfigDefinition, ObjectTypeComposer, SchemaComposer } from "graphql-compose"; const createOrderByEnum = (composer: SchemaComposer<any>) => { composer.getOrCreateETC("_OrderBy", etc => { etc.addFields({ asc: { description: `Sort ascending`, value: "asc" }, desc: { description: `Sort descending`, value: "desc" } }); }); }; const createOrderByInput = ( tc: ObjectTypeComposer, composer: SchemaComposer<any> ) => { const fields = tc.getFields(); const sortFields: { [key: string]: InputTypeComposerFieldConfigDefinition; } = {}; for (const fieldName in fields) { const field = fields[fieldName]; const isScalar = composer.isScalarType(field.type.getType()); if (isScalar) { sortFields[fieldName] = { type: "_OrderBy" }; } } composer.createInputTC({ name: `${tc.getTypeName()}OrderBy`, fields: sortFields, description: `Sort the field ` }); }; /** @internal */ export default (tc: ObjectTypeComposer, composer: SchemaComposer<any>) => { createOrderByEnum(composer); createOrderByInput(tc, composer); };
skimah/skimah
packages/api/src/resolvers/update.ts
import { getPluralName } from "graphql-compose"; import { parseResolveInfo, ResolveTree } from "graphql-parse-resolve-info"; import { ResolverDefinition } from "./index"; import createCreation from "../models/creation"; import { argsToCriteria } from "../models/selection"; /** * @internal * @param definition */ export default (definition: ResolverDefinition): string => { const { type: tc, models, datasources } = definition; const typeName = tc.getTypeName(); const pluralName = getPluralName(typeName); const name = getPluralName(`update${tc.getTypeName()}`); tc.addResolver({ name, description: `Update ${pluralName}`, type: `${typeName}MutationResponse`, args: { where: { type: `${tc.getTypeName()}Filter!`, description: `Update filter for ${pluralName}` }, changes: { type: definition.composer .getITC(`${tc.getTypeName()}Input`) .getTypeNonNull() } }, resolve: async ({ info }) => { const modelType = tc.getTypeName(); const baseModel = models[modelType]; const datasource = datasources[baseModel.datasource]; const tree = parseResolveInfo(info) as ResolveTree; const toBeUpdated = createCreation({ baseModel, values: tree.args.changes, models }); const criteria = argsToCriteria(tree.args, baseModel); return datasource.update(criteria, toBeUpdated); } }); return name; };
skimah/skimah
packages/api/test/models/selection.test.ts
import { graphql } from "graphql"; import generate from "../../src/generate"; import { QueryModel, Datasource } from "../../src/types"; const typeDefs = ` type User { userid: ID email: String username: String age: Int videos: [Video] @relation(field: "publisher") } type Video { videoID: ID name: String status: Status @relation publisher: User! @named(as: "user") @relation(field: "userid") comments: [Comment] @relation(field: "video") } interface Status { id: ID created_at: String vid: Video } type VideoStatus implements Status { id: ID created_at: String valid: Boolean vid: Video @relation @named(as: "video") } type Comment @datasource(name:"mongo") { id: ID text: String video: Video! @relation(field: "videoID") @named(as: "mediaID") } interface Entity { id: String } enum EntityType { Human Mammal } union Result = Comment | VideoStatus type Query { hello: String } `; const noopSource = () => ({ select: jest.fn(), create: jest.fn(), update: jest.fn(), delete: jest.fn() }); describe("Schema Selection", () => { test("Projection and identities", async () => { let selection: QueryModel; const { schema } = await generate({ typeDefs, sources: { mongo: noopSource(), default: { select: sel => { selection = sel; return Promise.all([]); }, create: jest.fn(), update: jest.fn(), delete: jest.fn() } } }); const query = ` query { findUsers { email username } } `; const result = await graphql(schema, query); expect(result.errors).toBeUndefined(); expect(selection.projectedAttributes).toMatchInlineSnapshot(` Object { "email": Object { "name": "email", "sourceName": "email", "type": "String", "unique": false, }, "userid": Object { "name": "userid", "sourceName": "userid", "type": "ID", "unique": true, }, "username": Object { "name": "username", "sourceName": "username", "type": "String", "unique": false, }, } `); expect(selection.identities).toMatchInlineSnapshot(` Array [ Object { "name": "userid", "sourceName": "userid", "type": "ID", "unique": true, }, ] `); expect(selection.datasource).toMatchInlineSnapshot(`"default"`); expect(selection.name).toMatchInlineSnapshot(`"User"`); }); test("Filter criteria", async () => { let selection: QueryModel; const { schema } = await generate({ typeDefs, sources: { mongo: noopSource(), default: { select: sel => { selection = sel; return Promise.all([]); }, create: jest.fn(), update: jest.fn(), delete: jest.fn() } } }); const query = ` query { findUsers(where: { username: { eq: "sayjava" }, age: { eq: 20 } } ) { username } } `; const result = await graphql(schema, query); expect(result.errors).toBeUndefined(); expect(selection.criteria).toMatchInlineSnapshot(` Object { "and": Array [ Object { "age": Object { "eq": 20, }, "username": Object { "eq": "sayjava", }, }, ], "limit": undefined, "or": Array [], "orderBy": Object {}, "skip": undefined, } `); }); test("OrderBy", async () => { let selection: QueryModel; const { schema } = await generate({ typeDefs, sources: { mongo: noopSource(), default: { select: sel => { selection = sel; return Promise.all([]); }, create: jest.fn(), update: jest.fn(), delete: jest.fn() } } }); const query = ` query { findUsers(orderBy: { age: asc } ) { username } } `; const result = await graphql(schema, query); expect(result.errors).toBeUndefined(); expect(selection.criteria).toMatchInlineSnapshot(` Object { "and": Array [], "limit": undefined, "or": Array [], "orderBy": Object { "age": "asc", }, "skip": undefined, } `); }); test("Combined filters", async () => { let selection: QueryModel; const { schema } = await generate({ typeDefs, sources: { mongo: noopSource(), default: { select: sel => { selection = sel; return Promise.all([]); }, create: jest.fn(), update: jest.fn(), delete: jest.fn() } } }); const query = ` query { findUsers(where: { age: { gte: 20 }, and: [ { username: { eq: "James" } }, { username: { eq: "Bond" } } ], or: [ { age: { gte: 5 } }, { age: { lte: 1 } } ] }) { username } } `; const result = await graphql(schema, query); expect(result.errors).toBeUndefined(); expect(selection.criteria).toMatchInlineSnapshot(` Object { "and": Array [ Object { "username": Object { "eq": "James", }, }, Object { "username": Object { "eq": "Bond", }, }, Object { "age": Object { "gte": 20, }, }, ], "limit": undefined, "or": Array [ Object { "age": Object { "gte": 5, }, }, Object { "age": Object { "lte": 1, }, }, ], "orderBy": Object {}, "skip": undefined, } `); }); test("Simple nested filters", async () => { let selection: QueryModel; const { schema } = await generate({ typeDefs, sources: { mongo: noopSource(), default: { select: sel => { selection = sel; return Promise.all([]); }, create: jest.fn(), update: jest.fn(), delete: jest.fn() } } }); const query = ` query { findUsers { videos(where : { name:{ eq: "trending" } }) { name status { created_at } } } } `; const result = await graphql(schema, query); expect(result.errors).toBeUndefined(); expect(selection.projectedRelations["videos"].condition) .toMatchInlineSnapshot(` Object { "child": Object { "name": "publisher", "sourceName": "user", }, "parent": Object { "name": "userid", "sourceName": "userid", }, } `); expect(selection.projectedRelations["videos"].model?.projectedAttributes) .toMatchInlineSnapshot(` Object { "name": Object { "name": "name", "sourceName": "name", "type": "String", "unique": false, }, "publisher": Object { "name": "publisher", "sourceName": "user", "type": "ID", "unique": false, }, "status": Object { "name": "status", "sourceName": "status", "type": "ID", "unique": false, }, "videoID": Object { "name": "videoID", "sourceName": "videoID", "type": "ID", "unique": true, }, } `); expect( (selection.projectedRelations["videos"].model as QueryModel).criteria ).toMatchInlineSnapshot(` Object { "and": Array [ Object { "name": Object { "eq": "trending", }, }, ], "limit": undefined, "or": Array [], "orderBy": Object {}, "skip": undefined, } `); expect( (selection.projectedRelations["videos"].model as QueryModel) .projectedAttributes ).toMatchInlineSnapshot(` Object { "name": Object { "name": "name", "sourceName": "name", "type": "String", "unique": false, }, "publisher": Object { "name": "publisher", "sourceName": "user", "type": "ID", "unique": false, }, "status": Object { "name": "status", "sourceName": "status", "type": "ID", "unique": false, }, "videoID": Object { "name": "videoID", "sourceName": "videoID", "type": "ID", "unique": true, }, } `); }); test("Nested criteria", async () => { let mongoSelection: QueryModel; const defaultSource: Datasource = { select: jest.fn(() => Promise.resolve([ { videoID: "first-video" } ]) ), create: jest.fn(), update: jest.fn(), delete: jest.fn() }; const mongoSource: Datasource = { select: jest.fn(selection => { mongoSelection = selection; return Promise.resolve([ { text: "first video comments" } ]); }), create: jest.fn(), update: jest.fn(), delete: jest.fn() }; const { schema } = await generate({ typeDefs, sources: { default: defaultSource, mongo: mongoSource } }); const query = ` query { findVideos { comments { text } } } `; const result = await graphql(schema, query); expect(result.errors).toBeUndefined(); expect(mongoSelection.criteria).toMatchInlineSnapshot(` Object { "and": Array [ Object { "mediaID": Object { "eq": "first-video", }, }, ], "limit": undefined, "or": Array [], "orderBy": Object {}, "skip": undefined, } `); }); test("Nested query of different datasources", async () => { let mongoSelection: QueryModel; const defaultSource: Datasource = { select: jest.fn(() => Promise.resolve([ { videoID: "first-video" } ]) ), create: jest.fn(), update: jest.fn(), delete: jest.fn() }; const mongoSource: Datasource = { select: jest.fn(selection => { mongoSelection = selection; return Promise.resolve([ { text: "first video comments" } ]); }), create: jest.fn(), update: jest.fn(), delete: jest.fn() }; const { schema } = await generate({ typeDefs, sources: { default: defaultSource, mongo: mongoSource } }); const query = ` query { findVideos { comments ( where: { text: { nin: ["yummy"] } }) { text } } } `; const result = await graphql(schema, query); expect(result.errors).toBeUndefined(); expect(mongoSelection.criteria).toMatchInlineSnapshot(` Object { "and": Array [ Object { "mediaID": Object { "eq": "first-video", }, "text": Object { "nin": Array [ "yummy", ], }, }, ], "limit": undefined, "or": Array [], "orderBy": Object {}, "skip": undefined, } `); expect(mongoSelection.projectedAttributes).toMatchInlineSnapshot(` Object { "id": Object { "name": "id", "sourceName": "id", "type": "ID", "unique": true, }, "text": Object { "name": "text", "sourceName": "text", "type": "String", "unique": false, }, "video": Object { "name": "video", "sourceName": "mediaID", "type": "ID", "unique": false, }, } `); }); test("Nested query only contains projectedRelations of same datasource", async () => { let defaultSelection: QueryModel; let mongoSelection: QueryModel; const defaultSource: Datasource = { select: jest.fn(selection => { defaultSelection = selection; return Promise.resolve([ { userId: "demo-person" } ]); }), create: jest.fn(), update: jest.fn(), delete: jest.fn() }; const mongoSource: Datasource = { select: jest.fn(selection => { mongoSelection = selection; return Promise.resolve([]); }), create: jest.fn(), update: jest.fn(), delete: jest.fn() }; const { schema } = await generate({ typeDefs, sources: { default: defaultSource, mongo: mongoSource } }); const query = ` query { findVideos { comments ( where: { text: { nin: ["yummy"] } }) { text } } } `; const result = await graphql(schema, query); expect(result.errors).toBeUndefined(); expect(mongoSelection.projectedRelations).toMatchInlineSnapshot( `Object {}` ); expect(defaultSelection.projectedRelations).toMatchInlineSnapshot( `Object {}` ); }); test("Query args", async () => { let selection: QueryModel; const { schema } = await generate({ typeDefs, sources: { mongo: noopSource(), default: { select: sel => { selection = sel; return Promise.all([]); }, create: jest.fn(), update: jest.fn(), delete: jest.fn() } } }); const query = ` query findMe($me:String) { findUsers(where: { username: { eq: $me }} ) { username } } `; const result = await graphql(schema, query, null, null, { me: "bond" }); expect(result.errors).toBeUndefined(); expect(selection.criteria).toMatchInlineSnapshot(` Object { "and": Array [ Object { "username": Object { "eq": "bond", }, }, ], "limit": undefined, "or": Array [], "orderBy": Object {}, "skip": undefined, } `); }); });
skimah/skimah
packages/api/src/models/base.ts
<reponame>skimah/skimah import { ComposeNamedOutputType, DirectiveArgs, ObjectTypeComposerFieldConfig, schemaComposer, unwrapOutputTC } from "graphql-compose"; import { Attribute, AttributeType, DefinedType, Model, Relation, RelationCondition } from "../types"; const isFieldUnique = ( /* eslint-disable @typescript-eslint/no-explicit-any */ field: ComposeNamedOutputType<any>, uniqueDirective: DirectiveArgs | void ): boolean => { return !!uniqueDirective || field.getTypeName() === "ID"; }; const getSourceNameForField = ( parent: DefinedType, fieldName: string ): string => { const fieldDirective = parent.getFieldDirectiveByName(fieldName, "named"); return fieldDirective ? fieldDirective.as : fieldName; }; /** * Retrieve the type identity field */ const typeIdentity = (tc: DefinedType): string => { const [uniqueField] = tc.getFieldNames().filter(fieldName => { return isFieldUnique( tc.getFieldTC(fieldName), tc.getFieldDirectiveByName(fieldName, "unique") ); }); if (!uniqueField) { throw Error(`${tc.getTypeName()} has no unique field`); } return uniqueField; }; const getFieldByTypeName = ( tc: DefinedType, typeName: string ): [string, ObjectTypeComposerFieldConfig<any, any, any>] => { const [firstFieldByType] = Object.entries(tc.getFields()).filter( ([, field]) => { const baseType = unwrapOutputTC(field.type).getTypeName(); return baseType === typeName; } ); return firstFieldByType; }; const relationships = { /** * One-to-Many relationship using `@relation` field * This will use the parent's unique identity to make connections to the child * This is because this is a virtual relationship that only * exists in the schema * * If the relation field is not specified, then use the field's type identity field */ oneToManyByDirective: ( relationField: string, parentOTC: DefinedType, parentField: string ): RelationCondition => { const parentUniqueField = typeIdentity(parentOTC); const childOTC = parentOTC.getFieldTC(parentField) as DefinedType; return { parent: { name: parentUniqueField, sourceName: getSourceNameForField(parentOTC, parentUniqueField) }, child: { name: relationField, sourceName: getSourceNameForField(childOTC, relationField) } }; }, /** * One-to-Many relationship using type inference. * This is useful when the `@relation`'s field parameter is omitted * * This type of relationship must be by-directional */ oneToManyByType: ( parentOTC: DefinedType, parentField: string ): RelationCondition => { const parentUniqueField = typeIdentity(parentOTC); const childOTC = parentOTC.getFieldTC(parentField) as DefinedType; try { const [parentInsideChild] = getFieldByTypeName( childOTC, parentOTC.getTypeName() ); return { parent: { name: parentUniqueField, sourceName: getSourceNameForField(parentOTC, parentUniqueField) }, child: { name: parentInsideChild, sourceName: getSourceNameForField(childOTC, parentInsideChild) } }; } catch { throw Error( `Without specifying @relation's field parameter, relationship definition must be bi-directional ${parentOTC.getTypeName()} -> ${childOTC.getTypeName()} ` ); } }, /** * One-to-One relationship using `@relation` field */ oneToOneByDirective: ( relationField: string, parentOTC: DefinedType, parentField: string ): RelationCondition => { const childOTC = parentOTC.getFieldTC(parentField) as DefinedType; return { parent: { name: parentField, sourceName: getSourceNameForField(parentOTC, parentField) }, child: { name: relationField, sourceName: getSourceNameForField(childOTC, relationField) } }; }, /** * One-to-One relationship using type inference. * This is useful when the `@relation`'s field parameter is omitted */ oneToOneByType: ( parentOTC: DefinedType, parentField: string ): RelationCondition => { const childOTC = parentOTC.getFieldTC(parentField) as DefinedType; try { const childUniqueIdentity = typeIdentity(childOTC); return { parent: { name: parentField, sourceName: getSourceNameForField(parentOTC, parentField) }, child: { name: childUniqueIdentity, sourceName: getSourceNameForField(childOTC, childUniqueIdentity) } }; } catch { throw Error( `Without specifying @relation's field parameter, relationship definition must be bi-directional ${parentOTC.getTypeName()} -> ${childOTC.getTypeName()} ` ); } } }; export default (tc: DefinedType): Model => { const attributes: { [key: string]: Attribute } = {}; const identities: Attribute[] = []; const relations: { [key: string]: Relation } = {}; /** * Rename the type name in the datasource `@named` directive */ const sourceName = ( tc.getDirectiveByName("named") || { as: tc.getTypeName() } ).as; /** * The datasource directive defaults to `default` if one is not provided */ const datasource = ( tc.getDirectiveByName("datasource") || { name: "default" } ).name; for (const [fieldName] of Object.entries(tc.getFields())) { const fieldTC = tc.getFieldTC(fieldName); /** * `@unique` directive or type of ID is used to determine if this is a unique field */ const isUnique = isFieldUnique( fieldTC, tc.getFieldDirectiveByName(fieldName, "unique") ); /** * Non scalar fields are treated as relationships */ const isRelation = !schemaComposer.isScalarType(fieldTC.getType()); const relationDirective = tc.getFieldDirectiveByName(fieldName, "relation"); /** * Is this field a collection */ const isCollection = tc.isFieldPlural(fieldName); /** * field renaming from @named(as:) directive */ const sourceName = getSourceNameForField(tc, fieldName); /** * Field type name like ID, String e.t.c */ const fieldTypeName = fieldTC.getTypeName() as AttributeType; /** * Create the attribute for model */ const attribute = { name: fieldName, sourceName, unique: isUnique, type: fieldTypeName }; // construct the relationship if (isRelation && relationDirective) { let condition: RelationCondition; // defined Relationships if (relationDirective.field) { // one-to-many if (isCollection) { condition = relationships.oneToManyByDirective( relationDirective.field, tc, fieldName ); } else { // one-to-one condition = relationships.oneToOneByDirective( relationDirective.field, tc, fieldName ); } } else { if (isCollection) { condition = relationships.oneToManyByType(tc, fieldName); } else { condition = relationships.oneToOneByType(tc, fieldName); } } // add relation condition to the attribute relations[fieldName] = { isCollection, condition, /** * Model will be added in the resolver phase */ model: null, ...attribute }; } else { // just attributes attributes[fieldName] = attribute; } isUnique && identities.push(attribute); } return { attributes, identities, relations, name: tc.getTypeName(), datasource, sourceName }; };
skimah/skimah
packages/api/test/response.test.ts
import generate from "../src/generate"; import { Datasource } from "../src/types"; const typeDefs = ` type User { userid: Int @unique firstName: String lastName: String emails: [String] } `; describe("Schema Mutation", () => { const defaultSource: Datasource = { select: jest.fn(), create: jest.fn(), update: jest.fn(), delete: jest.fn() }; test("response", async () => { const { schemaComposer } = await generate({ typeDefs, sources: { default: defaultSource } }); expect(schemaComposer.getOTC("UserMutationResponse").toSDL()) .toMatchInlineSnapshot(` "type UserMutationResponse { \\"\\"\\"The total number of users affected\\"\\"\\" affected: [ID!]! \\"\\"\\"The affected users\\"\\"\\" users: [User!]! }" `); }); });
skimah/skimah
packages/api/test/input.test.ts
<filename>packages/api/test/input.test.ts import { Datasource } from "../src/types"; import generate from "../src/generate"; const typeDefs = ` type User { userid: Int @unique firstName: String lastName: String emails: [String] profile: Profile @relation(field: "user", isOwner: true) posts: [Post] @relation(field: "author") categories: [Category!] } type Profile { id: ID @unique role: String user: User! @relation(field: "userid") } type Post { id: ID @unique text: String author: User! @relation(field: "userid") } type Category { type: String @unique } `; const defaultSource: Datasource = { select: jest.fn(), create: jest.fn(), update: jest.fn(), delete: jest.fn() }; describe("Schema Mutation Input", () => { let skimahResult; beforeEach(async () => { skimahResult = await generate({ typeDefs, sources: { default: defaultSource } }); }); test("basic", () => { expect(skimahResult.schemaComposer.getITC("UserInput").toSDL()) .toMatchInlineSnapshot(` "input UserInput { userid: Int firstName: String lastName: String emails: [String] profile: ID categories: [CategoryInput!] }" `); expect(skimahResult.schemaComposer.getITC("ProfileInput").toSDL()) .toMatchInlineSnapshot(` "input ProfileInput { id: ID role: String user: ID }" `); }); test("simple", () => { expect(skimahResult.schemaComposer.getITC("ProfileInput").toSDL()) .toMatchInlineSnapshot(` "input ProfileInput { id: ID role: String user: ID }" `); }); });
skimah/skimah
packages/api/src/resolvers/find.ts
import { getPluralName } from "graphql-compose"; import { parseResolveInfo, ResolveTree } from "graphql-parse-resolve-info"; import createSelection from "../models/selection"; import { ResolverDefinition } from "./index"; import { RelationCondition } from "../types"; /** * @internal * Creates a find{Type}s resolver that can be reused * for fetching a type. The datasource defined in the * schema for the type is invoked for sourcing this type * * The resolver will generate a {Criteria} from the graphql * query inputs that becomes the input to the datasource * * * @remarks * E.g for a type called User, a `findUsers` resolver is generated * * For fetching data across datasources, the relationship * that is declared between types in schema is automatically * inserted as a where clause into the criteria of the datasource * * e.g * type User { * id: ID * comments: [Comments] * } * * type Comments { * id: ID * text: String * * user: User `@relation` `@named(as: "user_id")` * } * * using an example query like this * * query { * findUsers { * comments { * text * } * } * } * * the Comment's datasource will receive an extra criteria filter * called `user_id` which will equal the id of the user automatically. * */ export default (definition: ResolverDefinition): string => { const { type: tc, models, datasources, interfaces } = definition; const resolverName = getPluralName(`find${tc.getTypeName()}`); const pluralName = getPluralName(tc.getTypeName()); tc.addResolver({ name: resolverName, type: tc.getTypePlural().getTypeNonNull(), args: { limit: { type: "Int", description: `Limit the number of ${pluralName} that will be returned` }, skip: { type: "Int", description: `Skip the first number of ${pluralName} that will be returned` }, where: { type: `${tc.getTypeName()}Filter`, description: `Filter condition for ${pluralName} that will be returned` }, orderBy: { type: `${tc.getTypeName()}OrderBy`, description: `Sort ${pluralName} that will be returned` } }, resolve: async ({ source: parent, info, context }) => { const modelType = tc.getTypeName(); const baseModel = models[modelType]; const modelSource = datasources[baseModel.datasource]; const tree = parseResolveInfo(info) as ResolveTree; let relationCondition: RelationCondition; /** * For fetching data from multiple datasources, * the connecting relationship is supplied to * the child as a `where` condition automatically * * If this query has a parent, * 1. Find the parent model and the relation * 2. Get the parent condition * 3. Add the child field to the args to be used eventually for creating * the query criteria */ if (parent) { const parentModel = models[info.parentType]; relationCondition = parentModel.relations[tree.name].condition; const parentField = parent[relationCondition.parent.name]; const filterCriteria = { [relationCondition.child.name]: { eq: parentField } }; if (tree.args.where) { Object.assign(tree.args.where, filterCriteria); } else { Object.assign(tree.args, { where: filterCriteria }); } } /** * If the call was a result of a mutation response, construct * a where in argument to be sent to the datasource. * Using the IDs of the newly created models, construct a where criteria */ if (context && context.mutationAffected) { const [id] = baseModel.identities; Object.assign(tree.args, { where: { [id.name]: { in: context.mutationAffected } } }); } const queryModel = createSelection({ models, baseModel, tree, interfaces }); /** * If there is a relation condition, make sure * the child condition is projected. * * Relation must be directional */ if (relationCondition) { const foreignRelation = queryModel.relations[relationCondition.child.name]; const foreignFieldName = relationCondition.child.name; if (foreignRelation) { queryModel.projectedAttributes[foreignFieldName] = { name: foreignRelation.name, sourceName: foreignRelation.sourceName, unique: false, type: "ID" }; } } const response = await modelSource.select(queryModel); if (info.returnType.toString().includes("[")) { return response; } else { return response[0]; } } }); return resolverName; };
skimah/skimah
packages/ds-faker/src/index.ts
export { default } from "./faker"; export { Config } from "./faker";
skimah/skimah
packages/api/src/resolvers/delete.ts
<gh_stars>1-10 import { getPluralName } from "graphql-compose"; import { parseResolveInfo, ResolveTree } from "graphql-parse-resolve-info"; import createSelection, { argsToCriteria } from "../models/selection"; import { ResolverDefinition } from "./index"; /** * @internal * Delete model resolver * * @summary * This resolver will use the `where` criteria supplied * in the graphql mutation argument to delete a set of models in the source * * If the resources to be deleted is requested, the resolver will first * selected the models using the same criteria from the datasource * then proceed with the deletion * * @param definition {ResolverDefinition} */ export default (definition: ResolverDefinition): string => { const { type: tc, models, datasources, interfaces } = definition; const typeName = tc.getTypeName(); const pluralName = getPluralName(typeName); const name = getPluralName(`delete${typeName}`); tc.addResolver({ name, description: `Delete ${pluralName}`, type: `${typeName}MutationResponse`, args: { where: { type: `${typeName}Filter!`, description: `Deletion filter for ${pluralName}` } }, resolve: async ({ info }) => { const modelType = tc.getTypeName(); const baseModel = models[modelType]; const datasource = datasources[baseModel.datasource]; const tree = parseResolveInfo(info) as ResolveTree; const projection = tree.fieldsByTypeName[`${tc.getTypeName()}MutationResponse`]; const recordProjection = projection[pluralName]; /** * If the models to be deleted is requested, then a select * operation is first conducted before deleting the models * * Use the same deletion criteria as the selection criteria */ if (recordProjection) { const queryModel = createSelection({ baseModel, tree: { ...recordProjection, args: tree.args }, models, interfaces }); const records = await datasource.select(queryModel); const deleted = await datasource.delete( queryModel.criteria, queryModel ); return { ...deleted, records }; } const criteria = argsToCriteria(tree.args, baseModel); return datasource.delete(criteria, baseModel); } }); return name; };
skimah/skimah
packages/ds-csv/src/index.ts
export { default } from "./csv"; export { Config } from "./csv";
skimah/skimah
example/index.ts
<filename>example/index.ts import { generate } from "@skimah/api"; import CsvSource from "@skimah/ds-csv"; import JsonSource from "@skimah/ds-json"; import { graphql } from "graphql"; const users = new CsvSource({ records: `id,user_name 1,james `, }); const tasks = new JsonSource({ records: [ { id: 1, title: "compile", done: false, owner: 1, }, { id: 2, title: "deploy", done: true, owner: 1, }, ], }); const sources = { users, tasks, }; const typeDefs = ` type User @datasource(name: "users") { id: ID userName: String @named(as: "user_name") tasks: [Task] @relation } type Task @datasource(name: "tasks") { id: ID title: String done: Boolean owner: User @relation } `; const query = `{ findUsers(limit: 1) { userName tasks(where: { done: { eq: true } }) { title } } }`; (async () => { // Generate executable schema const { schema } = await generate({ typeDefs, sources, }); // use whatever graphql server that suits you const result = await graphql({ schema, source: query, }); console.log(result.data.findUsers); })();
skimah/skimah
packages/api/test/orderby.test.ts
import { schemaComposer, ObjectTypeComposer } from "graphql-compose"; import addOrderby from "../src/orderby"; const typeDefs = ` type User { userid: Int firstName: String lastName: String } `; describe("Schema Orderby", () => { test("confirms order by", () => { const ts = schemaComposer.addTypeDefs(typeDefs); const tc = <ObjectTypeComposer>ts.get("User"); addOrderby(tc, schemaComposer); expect(tc.toSDL()).toMatchInlineSnapshot(` "type User { userid: Int firstName: String lastName: String }" `); expect(schemaComposer.getAnyTC("UserOrderBy").toSDL()) .toMatchInlineSnapshot(` "\\"\\"\\"Sort the field \\"\\"\\" input UserOrderBy { userid: _OrderBy firstName: _OrderBy lastName: _OrderBy }" `); expect(schemaComposer.getAnyTC("_OrderBy").toSDL()).toMatchInlineSnapshot(` "enum _OrderBy { \\"\\"\\"Sort ascending\\"\\"\\" asc \\"\\"\\"Sort descending\\"\\"\\" desc }" `); }); });
skimah/skimah
packages/api/src/inputs.ts
import { DirectiveArgs, ObjectTypeComposer, SchemaComposer } from "graphql-compose"; /** @internal */ export default (tc: ObjectTypeComposer, composer: SchemaComposer<any>) => { const itc = composer.getOrCreateITC(`${tc.getTypeName()}Input`, itc => { itc.merge(tc.getITC()); }); for (const [fieldName, fieldConfig] of Object.entries(itc.getFields())) { const fieldTC = tc.getFieldTC(fieldName); const relations = <DirectiveArgs>( tc.getFieldDirectiveByName(fieldName, "relation") ); const isCollection = tc.isFieldPlural(fieldName); if (relations) { // TODO: no support for one-to-many mutation if (isCollection) { itc.removeField(fieldName); } else { itc.setField(fieldName, { description: fieldConfig.description, type: `ID` }); } } } };
skimah/skimah
packages/ds-json/src/json.ts
<reponame>skimah/skimah import { Attribute, Criteria, CriteriaFilter, Datasource, Model, MutationModel, MutationResponse, QueryModel } from "@skimah/api"; import sift from "./sift"; export interface Config { /** * The path of the csv file that should be loaded */ filepath?: string; /** * An array of objects that should used instead of loading it from a file */ records?: any[]; } export default class implements Datasource { protected records: any[]; constructor(private config: Config) {} private loadFile(): any[] { const { readFileSync } = require("fs"); const jsonText = readFileSync(this.config.filepath); const rows = JSON.parse(jsonText.toString()); return rows; } private mapField(record: any, attributes: { [key: string]: Attribute }): any { const newRecord = {}; Object.keys(attributes).forEach(attrKey => { const attr = attributes[attrKey]; newRecord[attr.name] = record[attr.sourceName]; }); return newRecord; } private sort(rows: any[], model: QueryModel): any[] { try { const [[attr, order]] = Object.entries(model.criteria.orderBy || {}); return rows.sort((r1, r2) => { if (order === "asc") { return r1[attr] > r2[attr] ? 1 : -1; } return r2[attr] > r1[attr] ? 1 : -1; }); } catch { return rows; } } private page(rows: any[], model: QueryModel): any[] { if (model.criteria.skip || model.criteria.limit) { const skip = model.criteria.skip ?? 0; const limit = model.criteria.limit ? skip + model.criteria.limit : rows.length; return rows.slice(skip, limit); } return rows; } private criteria(criteria: Criteria) { const query = {}; const covertFilters = (filters: { [key: string]: CriteriaFilter }[]) => { return filters.map(c => { const [[field, filter]] = Object.entries(c); const newFilter = {}; Object.entries(filter).forEach(([key, value]) => { if (key === "like") { newFilter[`$regex`] = value; return; } newFilter[`$${key}`] = value; }); return { [field]: newFilter }; }); }; if (criteria.and.length) { const and = criteria.and.filter(c => Object.keys(c).length); Object.assign(query, { $and: covertFilters(and) }); } if (criteria.or.length) { const or = criteria.and.filter(c => Object.keys(c).length); Object.assign(query, { $or: covertFilters(or) }); } return query; } private filter(rows: any[], model: QueryModel): any[] { const query: any = this.criteria(model.criteria); const filtered = rows.filter(sift(query)); const mappedRows = filtered.map(row => this.mapField(row, model.projectedAttributes) ); const sorted = this.sort(mappedRows, model); const paged = this.page(sorted, model); return paged; } public async initialize(_: Model[]) { if (this.config.filepath) { this.records = this.loadFile(); } if (this.config.records) { this.records = this.config.records; } } public async create(models: MutationModel[]): Promise<MutationResponse<any>> { const affectedRecordIDs = []; const inputRecords = []; const sourceRecords = []; models.forEach(model => { const sourceRecord = {}; const inputRecord = {}; const [id] = model.identities; if (!id) { throw new Error(`${model.name} does not have a unique field`); } Object.values(model.mutatedAttributes).forEach(attr => { sourceRecord[attr.sourceName] = attr.value; inputRecord[attr.name] = attr.value; }); affectedRecordIDs.push(model.mutatedAttributes[id.name].value); inputRecords.push(inputRecord); sourceRecords.push(sourceRecord); }); this.records = this.records.concat(...sourceRecords); return { affected: affectedRecordIDs, records: inputRecords }; } public async select(selection: QueryModel): Promise<any[]> { const rows = this.filter(this.records, selection); return rows; } public async update( criteria: Criteria, changes: MutationModel ): Promise<MutationResponse<any>> { const query: any = this.criteria(criteria); const recordsToUpdate = this.records.filter(sift(query)); const affectedRecordIDs = []; const changedRecord = {}; Object.values(changes.mutatedAttributes).forEach(attr => { changedRecord[attr.sourceName] = attr.value; }); recordsToUpdate.forEach(recordToUpdate => { const responseRecord = {}; Object.assign(recordToUpdate, changedRecord); Object.values(changes.mutatedAttributes).forEach(attr => { responseRecord[attr.name] = recordToUpdate[attr.sourceName]; }); const [id] = changes.identities; affectedRecordIDs.push(recordToUpdate[id.sourceName]); }); return { affected: affectedRecordIDs }; } public async delete( criteria: Criteria, model: Model ): Promise<MutationResponse<any>> { const query: any = this.criteria(criteria); const recordsToDelete = this.records.filter(sift(query)); const [id] = model.identities; const affectedIDs = recordsToDelete.map(record => { return record[id.sourceName]; }); return { affected: affectedIDs }; } }
skimah/skimah
packages/api/src/models/utils.ts
import { ResolveTree } from "graphql-parse-resolve-info"; import { Attribute, Model, Relation } from "../types"; interface ModelArg { baseModel: Model; models: { [key: string]: Model }; tree: ResolveTree; } /** * Convert a graphql selectionSet to * */ export const graphFieldsToModel = ({ tree, baseModel, models }: ModelArg): Model => { const attributes: { [key: string]: Attribute } = {}; const relations: { [key: string]: Relation } = {}; const { fieldsByTypeName } = tree; const [[, projection]] = Object.entries(fieldsByTypeName); for (const [fieldName, fieldTree] of Object.entries(projection)) { if (baseModel.attributes[fieldName]) { attributes[fieldName] = baseModel.attributes[fieldName]; } else { const theRelation = { ...baseModel.relations[fieldName] }; relations[fieldName] = Object.assign(theRelation, { model: graphFieldsToModel({ baseModel: models[theRelation.type], models, tree: fieldTree }) }); } } return { ...baseModel, attributes, relations }; };
jwworth/typescript-node-module-starter
__tests__/index.test.ts
<reponame>jwworth/typescript-node-module-starter import { exampleFunction } from '../src/index'; test('exampleFunction/1', () => { expect(exampleFunction('Jake')).toMatch('Hello, Jake!'); });
luucasfarias/desafio_ceuma
managerapi-ui/src/app/students/student-search/student-search.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { StudentService, StudentFilter } from '../student.service'; import { LazyLoadEvent, ConfirmationService } from 'primeng/primeng'; import { ToastyService } from 'ng2-toasty'; import { ErrorHandlerService } from 'app/core/error-handler.service'; import { Title } from '@angular/platform-browser'; import { AuthService } from 'app/security/auth.service'; @Component({ selector: 'app-student-search', templateUrl: './student-search.component.html', styleUrls: ['./student-search.component.css'] }) export class StudentSearchComponent implements OnInit { totalRegisters = 0; filter = new StudentFilter(); // ? Instanciando a classe para ter acesso aos atributos students = []; @ViewChild('table') gridTable; // ? Injetano services constructor( private auth: AuthService, private studentService: StudentService, private toasty: ToastyService, private confirmation: ConfirmationService, private errorHandler: ErrorHandlerService, private title: Title ) { } ngOnInit() { this.title.setTitle('Pesquisa de alunos'); // this.search(); } search(page = 0) { this.filter.page = page; this.studentService.searchStudents(this.filter) .then(result => { this.totalRegisters = result.total; this.students = result.data; }).catch(error => this.errorHandler.handle(error)); } changePage(event: LazyLoadEvent) { const pages = event.first / event.rows; this.search(pages); console.log(event); } delete(student: any) { this.studentService.deleteStudents(student.id).then(() => { if (this.gridTable.first === 0) { this.search(); } else { this.gridTable.first = 0; } this.toasty.success('Aluno excluído com sucesso!'); }).catch(error => this.errorHandler.handle(error)); } confirmDelete(student: any) { this.confirmation.confirm( { message: 'Você tem certeza que seja excluir este aluno?', accept: () => { this.delete(student); } } ); } }
luucasfarias/desafio_ceuma
managerapi-ui/src/app/courses/courses.service.ts
import { Injectable } from '@angular/core'; import 'rxjs/add/operator/toPromise'; import { Course } from 'app/core/model'; import * as moment from 'moment'; import { AuthHttp } from 'angular2-jwt'; import { environment } from 'environments/environment'; @Injectable() export class CoursesService { courseUrl: string; constructor(private http: AuthHttp) { this.courseUrl = `${environment.apiURL}/courses`; } searchCourse(): Promise<any> { return this.http.get(`${this.courseUrl}`) .toPromise().then(response => response.json()); } deleteCourses(id: number): Promise<void> { return this.http.delete(`${this.courseUrl}/${id}`) .toPromise().then(() => null); } saveCourses(course: Course): Promise<Course> { return this.http.post(this.courseUrl, JSON.stringify(course)) .toPromise() .then(response => response.json()); } update(course: Course): Promise<Course> { return this.http.put(`${this.courseUrl}/${course.id}`, JSON.stringify(course)) .toPromise() .then(response => { const courseModificator = response.json() as Course; this.converterStringsParaDatas([courseModificator]); return courseModificator; }); } buscarPorCodigo(id: number): Promise<Course> { return this.http.get(`${this.courseUrl}/${id}`) .toPromise() .then(response => { const course = response.json() as Course; this.converterStringsParaDatas([course]); return course; }); } private converterStringsParaDatas(courses: Course[]) { for (const course of courses) { course.dateRegister = moment(course.dateRegister, 'YYYY-MM-DD').toDate(); } } }
luucasfarias/desafio_ceuma
managerapi-ui/src/app/courses/course-form/course-form.component.ts
<reponame>luucasfarias/desafio_ceuma<filename>managerapi-ui/src/app/courses/course-form/course-form.component.ts import { Component, OnInit } from '@angular/core'; import { CoursesService } from '../courses.service'; import { ToastyService } from 'ng2-toasty'; import { ConfirmationService } from 'primeng/primeng'; import { ErrorHandlerService } from 'app/core/error-handler.service'; import { Course } from 'app/core/model'; import { Title } from '@angular/platform-browser'; import { Router, ActivatedRoute } from '@angular/router'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-course-form', templateUrl: './course-form.component.html', styleUrls: ['./course-form.component.css'] }) export class CourseFormComponent implements OnInit { course = new Course(); constructor( private courseService: CoursesService, private toasty: ToastyService, private errorHandler: ErrorHandlerService, private route: ActivatedRoute, private routerDirect: Router, private title: Title ) { } ngOnInit() { this.title.setTitle('Cadastrar novo curso'); console.log(this.route.snapshot.params['id']); const idCourse = this.route.snapshot.params['id']; if (idCourse) { this.loadCourses(idCourse); } } get isEditing() { return Boolean(this.course.id); } loadCourses(id: number) { this.courseService.buscarPorCodigo(id).then(response => { this.course = response; this.updateTitleEdition(); }) .catch(error => this.errorHandler.handle(error)); } addingCourse(form: FormControl) { this.courseService.saveCourses(this.course) .then(() => { this.toasty.success('Curso cadastrado com sucesso!'); form.reset(); this.course = new Course(); }) .catch(error => this.errorHandler.handle(error)); console.log(this.course); } updateCourse(form: FormControl) { this.courseService.update(this.course).then(response => { this.course = response; this.toasty.success('Curso alterado com sucesso!'); this.updateTitleEdition(); }).catch(error => this.errorHandler.handle(error)); } save(form: FormControl) { if (this.isEditing) { this.updateCourse(form); } else { this.addingCourse(form); } } newCourse(form: FormControl) { form.reset(); this.course = new Course(); this.routerDirect.navigate(['/cursos/novo']); } cleanFields(form: FormControl) { form.reset(); this.course = new Course(); } updateTitleEdition() { this.title.setTitle(`Editar curso: ${this.course.name}`); } }
luucasfarias/desafio_ceuma
managerapi-ui/src/app/app-rounting.module.ts
<gh_stars>0 import { RouterModule, Routes } from '@angular/router'; import { NgModule } from '@angular/core'; import { CardComponent } from './core/card/card.component'; import { StudentSearchComponent } from './students/student-search/student-search.component'; import { StudentFormComponent } from './students/student-form/student-form.component'; import { PageNotFoundComponent } from './core/page-not-found.component'; import { CourseSearchComponent } from './courses/course-search/course-search.component'; import { CourseFormComponent } from './courses/course-form/course-form.component'; import { LoginComponent } from './security/login/login.component'; import { AuthGuard } from './security/auth.guard'; import { NotAuthorizedComponent } from './core/not-authorized.component'; const routes: Routes = [ // { path: '', component: CardComponent, pathMatch: 'full' }, { path: '', redirectTo: 'login', pathMatch: 'full' }, { path: 'login', component: LoginComponent }, { path: 'home', component: CardComponent }, { path: 'alunos', component: StudentSearchComponent, canActivate: [AuthGuard], data: { roles: ['ROLE_SEARCH_STUDENT'] } }, { path: 'alunos/novo', component: StudentFormComponent, canActivate: [AuthGuard], data: { roles: ['ROLE_REGISTER_STUDENT'] } }, { path: 'alunos/:id', component: StudentFormComponent, canActivate: [AuthGuard], data: { roles: ['ROLE_UPDATE_STUDENT'] } }, { path: 'cursos', component: CourseSearchComponent, canActivate: [AuthGuard], data: { roles: ['ROLE_SEARCH_COURSE'] } }, { path: 'cursos/novo', component: CourseFormComponent, canActivate: [AuthGuard], data: { roles: ['ROLE_REGISTER_COURSE'] } }, { path: 'cursos/:id', component: CourseFormComponent, canActivate: [AuthGuard], data: { roles: ['ROLE_UPDATE_COURSE'] } }, { path: 'nao-autorizado', component: NotAuthorizedComponent }, { path: 'pagina-nao-encontrada', component: PageNotFoundComponent }, { path: '**', redirectTo: 'pagina-nao-encontrada' }, ] @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ] }) export class AppRoutingModule { }
luucasfarias/desafio_ceuma
managerapi-ui/src/app/security/security.module.ts
<filename>managerapi-ui/src/app/security/security.module.ts<gh_stars>0 import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { LoginComponent } from './login/login.component'; import { InputTextModule, ButtonModule } from 'primeng/primeng'; import { FormsModule } from '@angular/forms'; import { AuthHttp, AuthConfig } from 'angular2-jwt'; import { Http, RequestOptions } from '@angular/http'; import { CeumaHttp } from './ceuma-http'; import { AuthService } from './auth.service'; import { AuthGuard } from './auth.guard'; import { LogoutService } from './logout.service'; export function authHttpServiceFactory(auth: AuthService, http: Http, options: RequestOptions) { const config = new AuthConfig({ globalHeaders: [ { 'Content-Type': 'application/json' } ] }); return new CeumaHttp(auth, config, http, options); } @NgModule({ imports: [ FormsModule, CommonModule, InputTextModule, ButtonModule ], declarations: [LoginComponent], exports: [LoginComponent], providers: [ { provide: AuthHttp, useFactory: authHttpServiceFactory, deps: [AuthService, Http, RequestOptions] }, AuthGuard, LogoutService ] }) export class SecurityModule { }
luucasfarias/desafio_ceuma
managerapi-ui/src/app/security/login/login.component.ts
import { Component, OnInit } from '@angular/core'; import { AuthService } from '../auth.service'; import { ErrorHandlerService } from 'app/core/error-handler.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { constructor( private auth: AuthService, private errorHandler: ErrorHandlerService, private router: Router ) { } ngOnInit() { } login(username_app: string, password_app: string) { this.auth.login(username_app, password_app) .then(() => { this.router.navigate(['/home']); }) .catch(error => { this.errorHandler.handle(error); }) } }
luucasfarias/desafio_ceuma
managerapi-ui/src/app/core/model.ts
export class Address { public_place: string; house_number: string; complement: string; neighborhood: string; cep: string; city: string; state: string; } export class Course { id: number; name: string; dateRegister: Date; workload: string; } export class Student { id: number; name: string; cpf: string; email: string; phone: string; course = new Course(); address = new Address(); }
luucasfarias/desafio_ceuma
managerapi-ui/src/app/courses/courses.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { DialogModule, InputTextModule, ButtonModule, DataTableModule, TooltipModule } from 'primeng/primeng'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { SharedModule } from 'app/shared/shared.module'; import { RouterModule } from '@angular/router'; import { CourseSearchComponent } from './course-search/course-search.component'; import { CourseFormComponent } from './course-form/course-form.component'; import { CalendarModule } from 'primeng/primeng'; @NgModule({ imports: [ CommonModule, BrowserAnimationsModule, FormsModule, InputTextModule, ButtonModule, DataTableModule, TooltipModule, DialogModule, RouterModule, CalendarModule, SharedModule ], declarations: [CourseSearchComponent, CourseFormComponent], exports: [] }) export class CoursesModule { }
luucasfarias/desafio_ceuma
managerapi-ui/src/environments/environment.prod.ts
<reponame>luucasfarias/desafio_ceuma export const environment = { production: true, // Adding url de servidor de prodution apiURL: 'https://ceuma-api.com' };
luucasfarias/desafio_ceuma
managerapi-ui/src/app/app.module.ts
import { AppComponent } from './app.component'; import { HttpModule } from '@angular/http'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { CoreModule } from './core/core.module'; import { StudentsModule } from './students/students.module'; import { CoursesModule } from './courses/courses.module'; import { AppRoutingModule } from './app-rounting.module'; import { SecurityModule } from './security/security.module'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, HttpModule, BrowserAnimationsModule, StudentsModule, CoursesModule, CoreModule, AppRoutingModule, SecurityModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
luucasfarias/desafio_ceuma
managerapi-ui/src/app/security/auth.service.ts
import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { JwtHelper } from 'angular2-jwt'; import { environment } from 'environments/environment'; @Injectable() export class AuthService { [x: string]: any; urlTokenJWT: string; jwtPayload: any; constructor( private htpp: Http, private jwtHelper: JwtHelper ) { this.urlTokenJWT = `${environment.apiURL}/oauth/token`; this.loadToken(); } login(username_app: string, password_app: string): Promise<void> { const headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); headers.append('Authorization', 'Basic YW5ndWxhcjpAbmd1bEBy'); const body = `username=${username_app}&password=${<PASSWORD>}&grant_type=password`; return this.htpp.post(this.urlTokenJWT, body, { headers, withCredentials: true }) .toPromise().then(response => { this.storeToken(response.json().access_token); console.log(response); }) .catch(response => { if (response.status === 400) { const responseJson = response.json(); if (responseJson.error === 'invalid_grant') { return Promise.reject('Usuário ou senha inválidos!'); } } return Promise.reject(response); }); } cleanAccessToken() { localStorage.removeItem('token'); this.jwtPayload = null; } isAccessTokenInvalid() { const token = localStorage.getItem('token'); return !token || this.jwtHelper.isTokenExpired(token); } getNewAccessToken(): Promise<void> { const headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); headers.append('Authorization', 'Basic YW5ndWxhcjpAbmd1bEBy'); const body = 'grant_type=refresh_token'; return this.http.post(this.urlTokenJWT, body, { headers, withCredentials: true }) .toPromise().then(response => { this.storeToken(response.json().access_token); console.log('TCL: Recebe novo accesse token do refresh: ', response); return Promise.resolve(null); }) .catch(response => { console.log('TCL:Erro ao renovar token: ', response); return Promise.resolve(null); }) } manyPermissions(roles) { for (const role of roles) { if (this.isAllowed(role)) { return true; } } return false; } isAllowed(permission: string) { return this.jwtPayload && this.jwtPayload.authorities.includes(permission); } private storeToken(token: string) { this.jwtPayload = this.jwtHelper.decodeToken(token); localStorage.setItem('token', token); } private loadToken() { const token = localStorage.getItem('token'); if (token) { this.storeToken(token); } } }
luucasfarias/desafio_ceuma
managerapi-ui/src/app/students/student.service.ts
<gh_stars>0 import { Injectable } from '@angular/core'; import { URLSearchParams } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { Student } from 'app/core/model'; import { AuthHttp } from 'angular2-jwt'; import { environment } from 'environments/environment'; export class StudentFilter { nameSearch: string; cpfSearch: string; page = 0; itemsPage = 6; } @Injectable() export class StudentService { studentsUrl: string; constructor(private http: AuthHttp) { this.studentsUrl = `${environment.apiURL}/students`; } searchStudents(filter: StudentFilter): Promise<any> { const params = new URLSearchParams(); params.set('page', filter.page.toString()); params.set('size', filter.itemsPage.toString()); if (filter.nameSearch) { params.set('name', filter.nameSearch); } if (filter.cpfSearch) { params.set('cpf', filter.cpfSearch); } return this.http.get(`${this.studentsUrl}?`, { search: params }) .toPromise().then(response => { const responseJson = response.json(); const students = responseJson.content; console.log('students: ', students); const result = { data: students, total: responseJson.totalElements }; return result; }); } deleteStudents(id: number): Promise<void> { return this.http.delete(`${this.studentsUrl}/${id}`) .toPromise().then(() => null); } saveStudents(student: Student): Promise<Student> { return this.http.post(this.studentsUrl, JSON.stringify(student)) .toPromise().then(response => response.json()); } update(student: Student): Promise<Student> { return this.http.put(`${this.studentsUrl}/${student.id}`, JSON.stringify(student)) .toPromise() .then(response => { const studentModificator = response.json(); return studentModificator; }); } buscarPorCodigo(id: number): Promise<Student> { return this.http.get(`${this.studentsUrl}/${id}`) .toPromise() .then(response => { const student = response.json(); return student; }); } }
luucasfarias/desafio_ceuma
managerapi-ui/src/app/core/core.module.ts
import { CommonModule } from '@angular/common'; import { NgModule, LOCALE_ID } from '@angular/core'; import { ToastyModule } from 'ng2-toasty'; import { ConfirmDialogModule, ConfirmationService } from 'primeng/primeng'; import { NavbarComponent } from './navbar/navbar.component'; import { ErrorHandlerService } from './error-handler.service'; import { StudentService } from 'app/students/student.service'; import { CoursesService } from 'app/courses/courses.service'; import { RouterModule } from '@angular/router'; import { CardComponent } from './card/card.component'; import { PageNotFoundComponent } from './page-not-found.component'; import { Title } from '@angular/platform-browser'; import { AuthService } from 'app/security/auth.service'; import { JwtHelper } from 'angular2-jwt'; import { NotAuthorizedComponent } from './not-authorized.component'; @NgModule({ imports: [ CommonModule, ToastyModule.forRoot(), ConfirmDialogModule, RouterModule ], declarations: [ NavbarComponent, CardComponent, PageNotFoundComponent, NotAuthorizedComponent ], exports: [ NavbarComponent, ToastyModule, ConfirmDialogModule ], providers: [ ErrorHandlerService, CoursesService, StudentService, ConfirmationService, Title, AuthService, JwtHelper, { provide: LOCALE_ID, useValue: 'pt-BR' } ] }) export class CoreModule { }
luucasfarias/desafio_ceuma
managerapi-ui/src/app/students/students.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { StudentSearchComponent } from './student-search/student-search.component'; import { FormsModule } from '@angular/forms'; import { InputTextModule, ButtonModule, DataTableModule, TooltipModule, DialogModule, DropdownModule } from 'primeng/primeng'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { StudentFormComponent } from './student-form/student-form.component'; import { SharedModule } from 'app/shared/shared.module'; import { RouterModule } from '@angular/router'; import { InputMaskModule } from 'primeng/primeng'; @NgModule({ imports: [ CommonModule, FormsModule, BrowserAnimationsModule, InputTextModule, ButtonModule, DataTableModule, TooltipModule, InputMaskModule, DialogModule, DropdownModule, RouterModule, SharedModule ], declarations: [StudentSearchComponent, StudentFormComponent], exports: [] }) export class StudentsModule { }
luucasfarias/desafio_ceuma
managerapi-ui/src/app/courses/course-search/course-search.component.ts
<gh_stars>0 import { Component, OnInit } from '@angular/core'; import { CoursesService } from '../courses.service'; import { ToastyService } from 'ng2-toasty'; import { ConfirmationService } from 'primeng/primeng'; import { ErrorHandlerService } from 'app/core/error-handler.service'; import { Course } from 'app/core/model'; import { FormControl } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { Title } from '@angular/platform-browser'; import { AuthService } from 'app/security/auth.service'; @Component({ selector: 'app-course-search', templateUrl: './course-search.component.html', styleUrls: ['./course-search.component.css'] }) export class CourseSearchComponent implements OnInit { dateValue: Date; courses = []; display: boolean = false; course = new Course(); ngOnInit() { this.title.setTitle('Pesquisa de cursos'); const idCourse = this.route.snapshot.params['id']; if (idCourse) { this.loadCourses(idCourse); } this.search(); } showDialog() { this.display = true; } constructor( private auth: AuthService, private courseService: CoursesService, private toasty: ToastyService, private confirmation: ConfirmationService, private errorHandler: ErrorHandlerService, private route: ActivatedRoute, private routerDirect: Router, private title: Title ) { } get isEditing() { return Boolean(this.course.id); } search() { this.courseService.searchCourse() .then(response => this.courses = response); } loadCourses(id: number) { this.courseService.buscarPorCodigo(id).then(response => { this.course = response; this.updateTitleEdition(); }) .catch(error => this.errorHandler.handle(error)); } delete(course: any) { this.courseService.deleteCourses(course.id).then(() => { this.search(); this.toasty.success('Curso excluído com sucesso!'); }).catch(error => this.errorHandler.handle(error)); } confirmDelete(student: any) { this.confirmation.confirm( { message: 'Você tem certeza que seja excluir este curso?', accept: () => { this.delete(student); } } ); } addingCourse(form: FormControl) { this.courseService.saveCourses(this.course).then(() => { this.toasty.success('Curso cadastrado com sucesso!'); form.reset(); this.course = new Course(); }) .catch(error => this.errorHandler.handle(error)); console.log(this.course); } updateCourse(form: FormControl) { this.courseService.update(this.course).then(response => { this.course = response; this.toasty.success('Curso alterado com sucesso!'); this.updateTitleEdition(); }).catch(error => this.errorHandler.handle(error)); } save(form: FormControl) { if (this.isEditing) { this.updateCourse(form); } else { this.addingCourse(form); } } cleanFields(form: FormControl) { form.reset(); this.course = new Course(); } updateTitleEdition() { this.title.setTitle(`Editar curso: ${this.course.name}`); } }
luucasfarias/desafio_ceuma
managerapi-ui/src/app/students/student-form/student-form.component.ts
import { Component, OnInit } from '@angular/core'; import { CoursesService } from 'app/courses/courses.service'; import { ErrorHandlerService } from 'app/core/error-handler.service'; import { Student } from 'app/core/model'; import { FormControl } from '@angular/forms'; import { StudentService } from '../student.service'; import { ToastyService } from 'ng2-toasty'; import { ActivatedRoute, Router } from '@angular/router'; import { Title } from '@angular/platform-browser'; @Component({ selector: 'app-student-form', templateUrl: './student-form.component.html', styleUrls: ['./student-form.component.css'] }) export class StudentFormComponent implements OnInit { courses = []; student = new Student(); constructor( private couseService: CoursesService, private studentService: StudentService, private errorHandler: ErrorHandlerService, private toasty: ToastyService, private route: ActivatedRoute, private routerDirect: Router, private title: Title ) { } ngOnInit() { this.title.setTitle('Cadastrar novo aluno(a)'); console.log(this.route.snapshot.params['id']); const idStudent = this.route.snapshot.params['id']; if (idStudent) { this.loadStudent(idStudent); } this.loadCourses(); } get isEditing() { return Boolean(this.student.id); } loadCourses() { return this.couseService.searchCourse() .then(response => { this.courses = response.map(c => { return { label: c.name, value: c.id }; }) }).catch(error => this.errorHandler.handle(error)); } loadStudent(id: number) { this.studentService.buscarPorCodigo(id).then(response => { this.student = response; this.updateTitleEdition(); }) .catch(error => this.errorHandler.handle(error)); } addingStudent(form: FormControl) { this.studentService.saveStudents(this.student) .then(() => { this.toasty.success('Aluno cadastrado com sucesso!'); form.reset(); this.student = new Student(); }) .catch(error => this.errorHandler.handle(error)); console.log(this.student); } updateStudent(form: FormControl) { this.studentService.update(this.student).then(response => { this.student = response; this.toasty.success('Aluno(a) alterado com sucesso!'); this.updateTitleEdition(); }).catch(error => this.errorHandler.handle(error)); } save(form: FormControl) { if (this.isEditing) { this.updateStudent(form); } else { this.addingStudent(form); } } newStudent(form: FormControl) { form.reset(); this.student = new Student(); this.routerDirect.navigate(['/alunos/novo']); } cleanFields(form: FormControl) { form.reset(); this.student = new Student(); } updateTitleEdition() { this.title.setTitle(`Editar aluno(a): ${this.student.name}`); } }
luucasfarias/desafio_ceuma
managerapi-ui/src/app/core/not-authorized.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-page-not-found', template: ` <div class="container"> <div class="ui-g-12"> <a routerLink="/home" class="back">Voltar</a> </div> <h1 class="text-center">Acesso negado!</h1> </div> `, styles: [] }) export class NotAuthorizedComponent implements OnInit { constructor() { } ngOnInit() { } }
luucasfarias/desafio_ceuma
managerapi-ui/src/app/core/error-handler.service.ts
<gh_stars>0 import { Injectable } from '@angular/core'; import { Response } from '@angular/http'; import { ToastyService } from 'ng2-toasty'; import { Router } from '@angular/router'; import { NotAuthenticatedError } from 'app/security/ceuma-http'; @Injectable() export class ErrorHandlerService { constructor(private toasty: ToastyService, private router: Router) { } handle(errorResponse: any) { let message: string; if (typeof errorResponse === 'string') { message = errorResponse; } else if (errorResponse instanceof NotAuthenticatedError) { message = 'Sua sessão expirou.'; this.router.navigate(['/login']); } // tslint:disable-next-line:one-line else if (errorResponse instanceof Response && errorResponse.status >= 400 && errorResponse.status <= 499) { message = 'Ocorreu um erro nesta solicitação'; console.log('Error message: ', message); if (errorResponse.status === 400) { message = 'Você não pode excluir um curso que está ativo.'; } if (errorResponse.status === 403) { message = 'Você não tem permissão para exclusão de alunos.'; } } else { message = 'Erro ao processar serviço remoto. Tente novamente.'; console.error('Ocorreu um erro', errorResponse); } this.toasty.error(message); } }
vishwanathovi/portfolio
src/pages/index.tsx
import * as React from 'react'; import Helmet from 'react-helmet'; import { Intro } from 'components/intro/Intro'; import { Highlight } from 'components/intro/Highlight'; import { Button } from 'components/button/Button'; import { FooterSpaceFiller } from 'components/footer-filler/FooterSpaceFiller'; import { BulletSection } from 'components/bullet-section/BulletSection'; export default () => ( <> <Helmet title="Vishwanath HM" /> <Intro> Hello, I am Vishwa 👋, <br/> A <Highlight>Frontend developer</Highlight> based out of Bangalore, India. <br/> I Enjoy coding in <Highlight>Javascript</Highlight> & most of the time i work on <Highlight>React</Highlight> and <Highlight>NodeJS</Highlight> projects.<br/><br/> Currently, I am open for Freelance projects/ Remote job opportunities. <br/><br/> <Button>Say Hi!</Button> </Intro> <BulletSection heading="Projects" bullets={[ {name:"FightIQ", link: "https://ueno.co", description: "A simple prediction application built for a Sports based startup"}, {name: "Harvard Art Gallery", link: "https://vishwanathovi.github.io/harvardartmuseum/", description: "One page gallery application built for Harvard Art Musuem"}, {name:"ISDB",link:"https://ueno.co",description:"India start-up companies database (Yet to be released)"} ]} /> <BulletSection heading="Contact" bullets={[ {name:"Github", link: "https://ueno.co", description: ""}, {name: "LinkedIn", link: "https://vishwanathovi.github.io/harvardartmuseum/", description: ""}, {name:"Email",link:"https://ueno.co",description:""} ]} /> <FooterSpaceFiller /> </> );
vishwanathovi/portfolio
src/components/footer/Footer.tsx
<gh_stars>0 import * as React from 'react'; import { Container } from 'components/container/Container'; const siteLogo = require('assets/images/vishwa.png'); import s from './Footer.scss'; interface ISocial { icon: React.ReactNode; to: string; } interface IFooterProps { logo: React.ReactNode; social: ISocial[]; } export const Footer = ({ logo, social }: IFooterProps) => ( <div className={s.footer}> <Container> <div className={s.footer__content}> <a href="/" rel="noopener noreferrer" > <img className={s.footer__logo_img} src={siteLogo} alt="site logo"/> </a> <ul className={s.footer__list}> {social.map((item) => ( <li key={item.to} className={s.footer__item} > <a href={item.to} target="_blank" rel="noopener noreferrer" > {item.icon} </a> </li> ))} </ul> </div> </Container> </div> );
vishwanathovi/portfolio
src/components/bullet-section/BulletSection.tsx
import * as React from 'react'; import { Container } from 'components/container/Container'; import { Row } from 'components/row/Row'; import s from './BulletSection.scss'; interface IBlockTextProps { heading: string; bullets: any; bullet: object; } export const BulletSection = ({ heading, bullets }: IBlockTextProps) => ( <Container> <div className={s.block}> <h1 className={s.block__heading}>{heading}</h1> <div className={s.block__col}> { bullets.map((bullet: { name: string; description: string; link: string;})=>( <div className={s.block__item} key={bullet.name}> <h3 className={s.block__item_header} > 🔅 <a className={s.block__item_link} href={bullet.link} target="_blank"> {bullet.name}</a> </h3> <p className={s.block__item_description}>{bullet.description}</p> </div> )) } </div> </div> </Container> );
vishwanathovi/portfolio
src/components/footer-filler/FooterSpaceFiller.tsx
import * as React from 'react'; import s from './FooterSpaceFiller.scss'; export const FooterSpaceFiller = () => ( <div className={s.footer_space_filler}></div> );
arvitaly/freeport-es6
__tests__/freeport-test.ts
<gh_stars>0 import freeport from "./.."; describe("FreePort", () => { it("get port", async () => { const port = await freeport(); expect(port > 0).toBeTruthy(); }); });
arvitaly/freeport-es6
index.ts
<filename>index.ts import { AddressInfo, createServer } from "net"; export default async () => { return new Promise<number>((resolve, reject) => { const server = createServer(); let port: number; server.once("listening", () => { const address = server.address() as AddressInfo; port = address.port; server.close(); }); server.once("close", () => { if (typeof port === "undefined") { reject("Can't get port"); return; } resolve(port); }); server.once("error", reject); server.listen(0, "127.0.0.1"); }); };
ericloureiro/schedules-challenge
client/src/types/utils.ts
<filename>client/src/types/utils.ts import { ReactNode } from 'react'; /* eslint-disable @typescript-eslint/no-explicit-any */ export type WithChildren<P = {}> = P & { children?: ReactNode; }; export type None = null | undefined; export type EmptyObject = Record<string, never>; export type ObjectOfAny = Record<string, any>; export type Empty = None | false | 0 | '' | [] | EmptyObject;
ericloureiro/schedules-challenge
client/src/hooks/useQueryData.ts
import constate from 'constate'; import { useState } from 'react'; import { getAllLogs } from 'src/api/logs'; import { getAllSchedules, toggleSchedule } from 'src/api/schedules'; import { LogsList } from 'src/types/logs'; import { Schedule, SchedulesList } from 'src/types/schedules'; type State = { selectedSchedule?: Schedule; schedules: SchedulesList; allLogs: LogsList; selectedLogs: LogsList; loading: boolean; error?: unknown; }; const initialState: State = { schedules: [], selectedLogs: [], allLogs: [], loading: false, }; const useQueryData = () => { const [state, setState] = useState<State>(initialState); const fetchAll = async () => { setState((current) => ({ ...current, loading: true })); try { const schedulesRequest = getAllSchedules(); const logsRequest = getAllLogs(); const [schedules, allLogs] = await Promise.all([schedulesRequest, logsRequest]); setState((current) => ({ ...current, loading: false, schedules, allLogs })); } catch (e) { setState((current) => ({ ...current, loading: false, error: e })); } }; const selectSchedule = (selectedSchedule: Schedule) => { const selectedLogs = state.allLogs.filter(({ scheduleId }) => selectedSchedule.id === scheduleId); setState((current) => ({ ...current, selectedLogs, selectedSchedule, })); }; const toggleScheduleRetire = async (schedule: Schedule) => { const newSchedule = await toggleSchedule(schedule); setState(({ schedules: currentSchedules, ...current }) => { const schedules = [...currentSchedules]; const index = schedules.findIndex(({ id }) => id === schedule.id); schedules[index] = newSchedule; return { ...current, schedules }; }); }; return { ...state, selectSchedule, toggleScheduleRetire, fetchAll, }; }; export const [QueryDataProvider, useQueryDataContext] = constate(useQueryData);
ericloureiro/schedules-challenge
client/src/types/schedules.ts
<reponame>ericloureiro/schedules-challenge import { Interval } from 'src/types/interval'; export type Schedule = { id: number; name: string; description: string; isRetired: boolean; tasksCount: number; startPoint: string; endPoint: string; dayOfWeek: number; dayOfMonth: number; startDate: string; endDate: string; intervalType?: Interval; timePeriod?: number; }; export type SchedulesList = Schedule[];
ericloureiro/schedules-challenge
client/src/types/status.ts
export type Status = 'Pending' | 'Running' | 'Terminated' | 'Completed' | 'Exception';
ericloureiro/schedules-challenge
client/src/tests/customRender.tsx
<reponame>ericloureiro/schedules-challenge import React from 'react'; import { render } from '@testing-library/react'; import { ReactElement } from 'react'; import { renderHook } from '@testing-library/react-hooks'; import { QueryDataProvider } from 'src/hooks/useQueryData'; import { WithChildren } from 'src/types/utils'; const wrapper = ({ children }: WithChildren) => <QueryDataProvider>{children}</QueryDataProvider>; const customRender = (ui: ReactElement) => render(ui, { wrapper }); const customRenderHook = <P, R>(customHook: (props: P) => R) => renderHook<P, R>(customHook, { wrapper }); // re-exports everything from @testing-library export * from '@testing-library/react'; // override default render and export export { customRender as render, customRenderHook as renderHook };
ericloureiro/schedules-challenge
client/src/constants/common.ts
export const HEADER_HEIGHT = 108;
ericloureiro/schedules-challenge
client/src/api/__tests__/fetch.spec.ts
<gh_stars>0 import { fetchApi } from 'src/api/fetch'; import { BASE_URL } from 'src/constants/config'; describe('fetch', () => { const mockUrl = ''; it('should return response as Object', async () => { fetchMock.once(JSON.stringify({}), { url: BASE_URL }); const response = await fetchApi<Object>(mockUrl); expect(response).toBeInstanceOf(Object); }); it('should throw error', async () => { expect.assertions(1); const error = new Error('Err'); fetchMock.once(() => { throw error; }); let err; try { await fetchApi<Object>(mockUrl); } catch (e) { err = e; } expect(error).toBe(err); }); it('should return !response.ok and throw error', async () => { expect.assertions(1); fetchMock.once(JSON.stringify({}), { url: BASE_URL, status: 500 }); let err; try { await fetchApi<Object>(mockUrl); } catch (e) { err = e; } expect(err).toBeDefined(); }); });
ericloureiro/schedules-challenge
client/src/tests/factories/interval.ts
import range from 'lodash.range'; import { Interval } from 'src/types/interval'; // TODO: add randomness to Interval enum // const interval = (): Interval => getRandomEnumValue(Status); const interval = (): Interval => 'Day'; const IntervalFactory = { create: () => interval(), createMany: (count = 5) => range(count).map(() => interval()), }; export default IntervalFactory;
ericloureiro/schedules-challenge
client/src/components/LogsList.tsx
<reponame>ericloureiro/schedules-challenge<gh_stars>0 import { Grid } from '@mui/material'; import React from 'react'; import PaddedTypography from 'src/components-shared/PaddedTypography'; import LogCard from 'src/components/LogCard'; import { LogsList as LogListType } from 'src/types/logs'; import { Schedule } from 'src/types/schedules'; import isEmpty from 'src/utils/isEmpty'; type Props = { logs: LogListType; selectedSchedule: Schedule | null; }; const LogsList = (props: Props) => { const { logs, selectedSchedule } = props; if (!selectedSchedule) { return ( <PaddedTypography color="white" variant="h5"> Please, select a Schedule </PaddedTypography> ); } if (isEmpty(logs)) { return ( <PaddedTypography color="white" variant="h5"> No logs found for schedule: {selectedSchedule.name} </PaddedTypography> ); } return ( <Grid style={{ padding: 8 }} rowSpacing={1} columnSpacing={{ xs: 1, sm: 2, md: 3 }} container> {logs.map((log) => ( <Grid key={`log-entry-${log.id}`} xs={12} sm={6} md={4} lg={3} item> <LogCard log={log} /> </Grid> ))} </Grid> ); }; export default LogsList;
ericloureiro/schedules-challenge
client/src/tests/factories/schedules.ts
import { Schedule } from 'src/types/schedules'; import faker from '@faker-js/faker'; import range from 'lodash.range'; import IntervalFactory from 'src/tests/factories/interval'; const scheduleBody = (params = {}): Schedule => ({ id: faker.datatype.number(), dayOfWeek: faker.datatype.number(), dayOfMonth: faker.datatype.number(), description: faker.commerce.productDescription(), endDate: faker.datatype.datetime().toDateString(), endPoint: faker.datatype.datetime().toDateString(), isRetired: faker.datatype.boolean(), name: faker.commerce.productName(), tasksCount: faker.datatype.number(), startDate: faker.datatype.datetime().toDateString(), startPoint: faker.datatype.datetime().toDateString(), intervalType: IntervalFactory.create(), ...params, }); const SchedulesFactory = { create: (params = {}) => scheduleBody(params), createMany: (count = 5, params = {}) => range(count).map(() => scheduleBody(params)), }; export default SchedulesFactory;
ericloureiro/schedules-challenge
client/src/tests/factories/logs.ts
import faker from '@faker-js/faker'; import range from 'lodash.range'; import StatusFactory from 'src/tests/factories/status'; import { Log } from 'src/types/logs'; const logBody = (params = {}): Log => ({ id: faker.datatype.number(), scheduleId: faker.datatype.number(), serverName: faker.commerce.productName(), endTime: faker.datatype.datetime().toDateString(), startTime: faker.datatype.datetime().toDateString(), status: StatusFactory.create(), ...params, }); const LogsFactory = { create: (params?: Partial<Log>) => logBody(params), createMany: (count = 5, params?: Partial<Log>) => range(count).map(() => logBody(params)), }; export default LogsFactory;
ericloureiro/schedules-challenge
client/src/api/__tests__/schedules.spec.ts
import { getAllSchedules, toggleSchedule } from 'src/api/schedules'; import { SCHEDULES } from 'src/constants/api'; import { BASE_URL } from 'src/constants/config'; import SchedulesFactory from 'src/tests/factories/schedules'; import { mockSchedules } from 'src/tests/mocks'; describe('schedules', () => { it('should GET all schedules', async () => { fetchMock.once(JSON.stringify(mockSchedules), { url: BASE_URL + '/' + SCHEDULES }); const response = await getAllSchedules(); expect(response).toMatchObject(mockSchedules); }); it('should PATCH a schedule', async () => { const mockSchedule = SchedulesFactory.create(); fetchMock.once(JSON.stringify(mockSchedule), { url: BASE_URL + '/' + SCHEDULES, headers: { 'Content-type': 'application/json' }, }); const response = await toggleSchedule(mockSchedule); expect(response).toMatchObject(mockSchedule); }); });
ericloureiro/schedules-challenge
client/src/App.tsx
import React, { useEffect, useState } from 'react'; import ScrollableGrid from 'src/components-shared/ScrollableGrid'; import { useQueryDataContext } from 'src/hooks/useQueryData'; import PaddedTypography from 'src/components-shared/PaddedTypography'; import LogsList from 'src/components/LogsList'; import SchedulesList from 'src/components/SchedulesList'; import SearchInput from 'src/components/SearchInput'; import { AppContainer } from 'src/styles'; import { AppBar, CircularProgress, Grid, Toolbar, Typography } from '@mui/material'; import isEmpty from 'src/utils/isEmpty'; const App = () => { const { fetchAll, selectSchedule, toggleScheduleRetire, schedules, selectedLogs, selectedSchedule, loading, error } = useQueryDataContext(); const [searchTerm, setSearchTerm] = useState(''); useEffect(() => { fetchAll(); }, []); if (!isEmpty(error)) { return <Typography>I'm a friendly error :)</Typography>; } return ( <AppContainer> <AppBar color={'default'} position="static"> <Toolbar> <SearchInput label={'Schedules Search'} onChange={setSearchTerm} /> {selectedSchedule && <PaddedTypography color="black">{selectedSchedule.name}</PaddedTypography>} </Toolbar> </AppBar> {loading ? ( <CircularProgress /> ) : ( <Grid container> <ScrollableGrid item xs={8} sm={4}> <SchedulesList selectSchedule={selectSchedule} toggleScheduleRetire={toggleScheduleRetire} schedules={schedules} searchTerm={searchTerm} /> </ScrollableGrid> <ScrollableGrid item xs> <LogsList logs={selectedLogs} selectedSchedule={selectedSchedule} /> </ScrollableGrid> </Grid> )} </AppContainer> ); }; export default App;
ericloureiro/schedules-challenge
client/src/tests/factories/status.ts
import { Status } from 'src/types/status'; import range from 'lodash.range'; // TODO: add randomness to Status enum // const statusBody = (): Status => getRandomEnumValue(Status); const statusBody = (): Status => 'Completed'; const StatusFactory = { create: () => statusBody(), createMany: (count = 5) => range(count).map(() => statusBody()), }; export default StatusFactory;
ericloureiro/schedules-challenge
client/src/api/__tests__/logs.spec.ts
import { getAllLogs } from 'src/api/logs'; import { SCHEDULE_LOGS } from 'src/constants/api'; import { BASE_URL } from 'src/constants/config'; import { mockLogs } from 'src/tests/mocks'; describe('logs', () => { it('should GET all logs', async () => { fetchMock.once(JSON.stringify(mockLogs), { url: BASE_URL + '/' + SCHEDULE_LOGS }); const response = await getAllLogs(); expect(response).toMatchObject(mockLogs); }); });
ericloureiro/schedules-challenge
client/src/components-shared/ScrollableGrid.tsx
import styled from '@emotion/styled'; import { Grid } from '@mui/material'; import { HEADER_HEIGHT } from 'src/constants/common'; const ScrollableGrid = styled(Grid)({ maxHeight: `calc(100vh - ${HEADER_HEIGHT}px)`, justifyContent: 'center', overflow: 'auto', }); export default ScrollableGrid;
ericloureiro/schedules-challenge
client/src/styles.ts
import styled from '@emotion/styled'; import { Grid } from '@mui/material'; const grey = '#282c34'; export const AppContainer = styled(Grid)` overflow: hidden; height: 100vh; width: 100vw; background-color: ${grey}; `;
ericloureiro/schedules-challenge
client/src/components/ScheduleCard.tsx
import styled from '@emotion/styled'; import { Card, CardActionArea, CardActions, CardContent, CardHeader, Chip, Divider, IconButton, Stack, Typography, } from '@mui/material'; import StarBorderIcon from '@mui/icons-material/StarBorder'; import StarIcon from '@mui/icons-material/Star'; import React, { useMemo } from 'react'; import { Schedule } from 'src/types/schedules'; type Props = { schedule: Schedule; onSelect: () => void; onToggle: () => Promise<void>; }; const StyledCard = styled(Card)` display: flex; align-content: space-around; flex-direction: column; justify-content: center; `; const StyledCardActionArea = styled(CardActionArea)({ flex: 1, alignItems: 'flex-start', }); const StyledCardActions = styled(CardActions)({ display: 'flex', justifyContent: 'space-between', padding: 8, }); const ScheduleCard = (props: Props) => { const { schedule, onToggle, onSelect } = props; const { id, name, description, isRetired } = schedule; const ScheduleActions = useMemo(() => { const { Icon, StatusChip } = isRetired ? { Icon: StarBorderIcon, StatusChip: () => <Chip label={'Retired'} color={'error'} />, } : { Icon: StarIcon, StatusChip: () => <Chip label={'Active'} color={'success'} />, }; return () => ( <StyledCardActions> <Stack direction={'row'} spacing={2} divider={<Divider orientation="vertical" flexItem />}> <Typography>Status</Typography> <StatusChip /> </Stack> <IconButton className="toggle-button" onClick={onToggle}> <Icon color={'primary'} /> </IconButton> </StyledCardActions> ); }, [isRetired, onToggle]); return ( <StyledCard className={`schedule-card-${id}`}> <StyledCardActionArea onClick={onSelect}> <CardHeader title={name}></CardHeader> <CardContent> <Typography variant="body2" color="text.secondary"> {description} </Typography> </CardContent> </StyledCardActionArea> <ScheduleActions /> </StyledCard> ); }; export default ScheduleCard;
ericloureiro/schedules-challenge
client/src/components-shared/PaddedTypography.tsx
import styled from '@emotion/styled'; import { Typography } from '@mui/material'; const PaddedTypography = styled(Typography)({ padding: 16, }); export default PaddedTypography;
ericloureiro/schedules-challenge
client/src/components/LogCard.tsx
<gh_stars>0 import styled from '@emotion/styled'; import { Card, CardActions, CardContent, Chip, Typography } from '@mui/material'; import React from 'react'; import { ChipColor } from 'src/types/colors'; import { Log } from 'src/types/logs'; import { Status } from 'src/types/status'; type Props = { log: Log; }; const StatusMap: Record<Status, ChipColor> = { Pending: 'default', Running: 'primary', Terminated: 'error', Completed: 'success', Exception: 'warning', }; const StyledCard = styled(Card)({ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', minHeight: 180, '&:hover': { transform: 'scale3d(1.05, 1.05, 1)' }, }); const StyledCardActions = styled(CardActions)({ display: 'flex', justifyContent: 'flex-end', }); const LogCard = (props: Props) => { const { log } = props; const { serverName, status } = log; return ( <StyledCard style={{ backgroundColor: StatusMap[status] }}> <CardContent> <Typography>{serverName}</Typography> </CardContent> <StyledCardActions> <Chip variant="outlined" color={StatusMap[status]} label={status} /> </StyledCardActions> </StyledCard> ); }; export default LogCard;
ericloureiro/schedules-challenge
client/src/types/logs.ts
import { Status } from 'src/types/status'; export type Log = { id: number; startTime: string; endTime: string; status: Status; serverName: string; scheduleId: number; }; export type LogsList = Log[];
ericloureiro/schedules-challenge
client/src/components/__tests__/SchedulesList.spec.tsx
import React from 'react'; import SchedulesList from 'src/components/SchedulesList'; import { render } from 'src/tests/customRender'; import SchedulesFactory from 'src/tests/factories/schedules'; const mockSelectSchedule = jest.fn(); const mockToggleScheduleRetire = jest.fn(); const mockSchedules = SchedulesFactory.createMany(); describe('ScheduleList', () => { const renderList = () => render( <SchedulesList selectSchedule={mockSelectSchedule} toggleScheduleRetire={mockToggleScheduleRetire} schedules={mockSchedules} searchTerm={''} /> ); it('render list of schedules cards', () => { const { getByText } = renderList(); mockSchedules.forEach(({ name }) => expect(getByText(name)).toBeDefined()); }); });
ericloureiro/schedules-challenge
client/jest.config.ts
<filename>client/jest.config.ts import type { Config } from '@jest/types'; const config: Config.InitialOptions = { verbose: true, setupFilesAfterEnv: ['<rootDir>/src/tests/setup.tsx'], moduleDirectories: ['node_modules', 'src'], moduleFileExtensions: ['ts', 'tsx', 'js'], rootDir: './', testEnvironment: 'jsdom', automock: false, modulePaths: ['<rootDir>'], collectCoverageFrom: [ 'src/**/*.{ts,tsx}', '!src/**/*.stories.tsx', '!node_modules/', '!src/constants/*', '!src/tests/*', '!src/tests/factories/*', '!src/types/*', '!src/types/declarations/*', ], coverageReporters: ['text'], coverageThreshold: { global: { branches: 90, functions: 90, lines: 90, statements: 90, }, }, // Remove errors when importing these type of files on tests moduleNameMapper: { '\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga|css|less)$': '<rootDir>/src/tests/setup.tsx', }, }; export default config;
ericloureiro/schedules-challenge
client/src/tests/utils.ts
<reponame>ericloureiro/schedules-challenge<filename>client/src/tests/utils.ts export const getRandomEnum = <T extends object>(anEnum: T): T[keyof T] => { const enumValues = Object.keys(anEnum) .filter((key) => typeof anEnum[key as keyof typeof anEnum] === 'number') .map((key) => key); const randomIndex = Math.floor(Math.random() * enumValues.length); return anEnum[randomIndex as keyof T]; }; export function getRandomEnumValue<T>(anEnum: T): T[keyof T] { //save enums inside array const enumValues = Object.keys(anEnum) as Array<keyof T>; //Generate a random index (max is array length) const randomIndex = Math.floor(Math.random() * enumValues.length); // get the random enum value const randomEnumKey = enumValues[randomIndex]; return anEnum[randomEnumKey]; // if you want to have the key than return randomEnumKey }
ericloureiro/schedules-challenge
client/src/components/SearchInput.tsx
import { TextField } from '@mui/material'; import React from 'react'; import throttle from 'lodash/throttle'; type Props = { label: string; onChange: (term: string) => void; }; const SearchInput = (props: Props) => { const { onChange, label } = props; const searchTermDebounce = throttle(onChange, 1500); const onInputChange = ({ target }: React.ChangeEvent<HTMLInputElement>) => { searchTermDebounce(target.value); }; return <TextField style={{ minWidth: 180, padding: 16 }} autoFocus placeholder={label} onChange={onInputChange} />; }; export default SearchInput;
ericloureiro/schedules-challenge
client/src/utils/__tests__/isEmpty.spec.ts
import isEmpty from 'src/utils/isEmpty'; describe('isEmpty', () => { it('return true with empty object', () => { expect(isEmpty({})).toEqual(true); }); it('return true with empty array', () => { expect(isEmpty([])).toEqual(true); }); it('return true with null or undefined', () => { expect(isEmpty(null)).toEqual(true); expect(isEmpty(undefined)).toEqual(true); }); it('return true with empty string', () => { expect(isEmpty('')).toEqual(true); }); it('return true with zero', () => { expect(isEmpty(0)).toEqual(true); expect(isEmpty('0')).toEqual(true); }); it('return true with false', () => { expect(isEmpty(false)).toEqual(true); }); it('return false with any value', () => { expect(isEmpty('a')).toEqual(false); expect(isEmpty(1)).toEqual(false); expect(isEmpty([1, 2, 3])).toEqual(false); expect(isEmpty({ a: 1 })).toEqual(false); expect(isEmpty(true)).toEqual(false); }); });
ericloureiro/schedules-challenge
client/src/hooks/__tests__/useQueryData.spec.ts
import { act } from 'react-test-renderer'; import { useQueryDataContext } from 'src/hooks/useQueryData'; import { renderHook } from 'src/tests/customRender'; import { mockLogs, mockSchedules } from 'src/tests/mocks'; import { Schedule } from 'src/types/schedules'; const mockGetAllLogs = jest.fn(() => Promise.resolve(mockLogs)); jest.mock('src/api/logs', () => ({ getAllLogs: () => mockGetAllLogs(), })); const mockGetAllSchedules = jest.fn(() => Promise.resolve(mockSchedules)); jest.mock('src/api/schedules', () => ({ getAllSchedules: () => mockGetAllSchedules(), toggleSchedule: (schedule: Schedule) => Promise.resolve({ ...schedule, isRetired: !schedule.isRetired }), })); describe('useQueryData', () => { it('should render initial state', () => { const { result: { current }, } = renderHook(useQueryDataContext); const { allLogs, schedules, selectedSchedule, error, loading, selectedLogs } = current; expect(allLogs).toStrictEqual([]); expect(schedules).toStrictEqual([]); expect(selectedLogs).toStrictEqual([]); expect(selectedSchedule).toBeUndefined(); expect(loading).toBeFalsy(); expect(error).toBeFalsy(); }); it('should fetchAll', async () => { const { result } = renderHook(useQueryDataContext); expect(result.current.allLogs).toStrictEqual([]); expect(result.current.schedules).toStrictEqual([]); await act(result.current.fetchAll); const { allLogs, schedules } = result.current; expect(allLogs).toStrictEqual(mockLogs); expect(allLogs).toHaveLength(mockLogs.length); expect(schedules).toStrictEqual(mockSchedules); expect(schedules).toHaveLength(mockSchedules.length); }); it('should select Schedule', async () => { const { result } = renderHook(useQueryDataContext); expect(result.current.selectedSchedule).toBeUndefined(); const [mockSchedule] = mockSchedules; await act(() => result.current.selectSchedule(mockSchedule)); expect(result.current.selectedSchedule).toBe(mockSchedule); }); it('should toggle Schedule', async () => { const { result } = renderHook(useQueryDataContext); await act(result.current.fetchAll); const [schedule] = result.current.schedules; await act(() => result.current.toggleScheduleRetire(schedule)); const newSchedule = result.current.schedules.find(({ id }) => id === schedule.id); expect(newSchedule).toMatchObject({ ...schedule, isRetired: !schedule.isRetired }); }); it('should handle error state', async () => { mockGetAllLogs.mockRejectedValueOnce(Error('Err')); mockGetAllSchedules.mockRejectedValueOnce(Error('Err')); const { result } = renderHook(useQueryDataContext); expect(result.current.error).toBeUndefined(); await act(result.current.fetchAll); expect(result.current.error).toBeTruthy(); }); it('should handle loading state', async () => { const { result, waitForNextUpdate } = renderHook(useQueryDataContext); expect(result.current.loading).toBeFalsy(); act(result.current.fetchAll); expect(result.current.loading).toBeTruthy(); await waitForNextUpdate(); expect(result.current.loading).toBeFalsy(); }); });
ericloureiro/schedules-challenge
client/src/api/fetch.ts
<reponame>ericloureiro/schedules-challenge<filename>client/src/api/fetch.ts import { BASE_URL } from 'src/constants/config'; export const fetchApi = async <T>(params: string, init?: RequestInit) => { const response = await fetch(BASE_URL + params, init); if (!response.ok) throw Error(response.statusText); const objectT: T = await response.json(); return objectT; };
ericloureiro/schedules-challenge
client/src/types/declarations/theme.d.ts
<reponame>ericloureiro/schedules-challenge<gh_stars>0 import { Theme } from '@material-ui/core'; declare module '@material-ui/styles' { interface DefaultTheme extends Theme {} } declare module '@material-ui/core/styles' { interface Theme extends DefaultTheme { status: { danger: string; }; } // allow configuration using `createTheme` interface ThemeOptions extends DefaultTheme { status?: { danger?: string; }; } }
ericloureiro/schedules-challenge
client/src/components/SchedulesList.tsx
<filename>client/src/components/SchedulesList.tsx import { Grid } from '@mui/material'; import React, { useMemo } from 'react'; import PaddedTypography from 'src/components-shared/PaddedTypography'; import ScheduleCard from 'src/components/ScheduleCard'; import { Schedule, SchedulesList as SchedulesListType } from 'src/types/schedules'; import isEmpty from 'src/utils/isEmpty'; type Props = { selectSchedule: (schedule: Schedule) => void; toggleScheduleRetire: (schedule: Schedule) => Promise<void>; schedules: SchedulesListType; searchTerm: string; }; const SchedulesList = (props: Props) => { const { selectSchedule, toggleScheduleRetire, schedules, searchTerm } = props; const onSelect = (schedule: Schedule) => () => selectSchedule(schedule); const onToggle = (schedule: Schedule) => () => toggleScheduleRetire(schedule); const filteredSchedules = useMemo(() => { if (isEmpty(searchTerm)) return schedules; const lowerCaseTerm = searchTerm.toLowerCase(); return schedules.filter( ({ id, name, description }) => id.toString().toLowerCase().includes(lowerCaseTerm) || name.toLowerCase().includes(lowerCaseTerm) || description.toLowerCase().includes(lowerCaseTerm) ); }, [schedules, searchTerm]); if (searchTerm && isEmpty(schedules)) { return <PaddedTypography variant="h5">No schedules found on search!</PaddedTypography>; } return ( <Grid style={{ padding: 8 }} rowSpacing={1} container> {filteredSchedules.map((schedule) => ( <Grid key={`schedule-card-${schedule.id}`} item xs={12}> <ScheduleCard schedule={schedule} onSelect={onSelect(schedule)} onToggle={onToggle(schedule)} /> </Grid> ))} </Grid> ); }; export default SchedulesList;
ericloureiro/schedules-challenge
client/src/api/logs.ts
import { fetchApi } from 'src/api/fetch'; import { SCHEDULE_LOGS } from 'src/constants/api'; import { LogsList } from 'src/types/logs'; export const getAllLogs = () => fetchApi<LogsList>(SCHEDULE_LOGS);
ericloureiro/schedules-challenge
client/src/types/interval.ts
<gh_stars>0 export type Interval = 'Never' | 'Once' | 'Hour' | 'Day' | 'Week' | 'Month' | 'Year' | 'Minute' | 'Second';
ericloureiro/schedules-challenge
client/src/components/__tests__/ScheduleCard.spec.tsx
<filename>client/src/components/__tests__/ScheduleCard.spec.tsx import React from 'react'; import ScheduleCard from 'src/components/ScheduleCard'; import { render } from 'src/tests/customRender'; import SchedulesFactory from 'src/tests/factories/schedules'; import { fireEvent } from '@testing-library/react'; describe('ScheduleCard', () => { const mockSchedule = SchedulesFactory.create(); const mockOnToggle = jest.fn(); const mockOnSelect = jest.fn(); describe('should render', () => { const renderCard = () => render(<ScheduleCard schedule={mockSchedule} onToggle={mockOnToggle} onSelect={mockOnSelect} />); it('schedule name', () => { const { getByText } = renderCard(); const name = getByText(mockSchedule.name); expect(name).toBeDefined(); }); it('schedule description', () => { const { getByText } = renderCard(); const description = getByText(mockSchedule.description); expect(description).toBeDefined(); }); it('Status information', () => { const { getByText } = renderCard(); const statusText = getByText('Status'); expect(statusText).toBeDefined(); }); it('when retired', () => { mockSchedule.isRetired = true; const { getByTestId, getByText } = renderCard(); const statusChip = getByText('Retired'); const starIcon = getByTestId('StarBorderIcon'); expect(statusChip).toBeDefined(); expect(starIcon).toBeDefined(); }); it('when active', () => { mockSchedule.isRetired = false; const { getByTestId, getByText } = renderCard(); const statusChip = getByText('Active'); const starBorderIcon = getByTestId('StarIcon'); expect(statusChip).toBeDefined(); expect(starBorderIcon).toBeDefined(); }); it('call select schedule', () => { const { getAllByRole } = renderCard(); const [selectButton] = getAllByRole('button'); fireEvent.click(selectButton); expect(mockOnSelect).toBeCalledTimes(1); }); it('call onToggle retire and unretire', () => { const { getAllByRole } = renderCard(); const [, toggleButton] = getAllByRole('button'); fireEvent.click(toggleButton); expect(mockOnToggle).toBeCalledTimes(1); }); }); });
ericloureiro/schedules-challenge
client/src/tests/mocks.ts
import LogsFactory from 'src/tests/factories/logs'; import SchedulesFactory from 'src/tests/factories/schedules'; export const mockLogs = LogsFactory.createMany(5); export const mockSchedules = SchedulesFactory.createMany(5);
ericloureiro/schedules-challenge
client/src/constants/api.ts
export const SCHEDULE_LOGS = 'scheduleLogs'; export const SCHEDULES = 'schedules';
ericloureiro/schedules-challenge
client/src/api/schedules.ts
<reponame>ericloureiro/schedules-challenge<filename>client/src/api/schedules.ts<gh_stars>0 import { fetchApi } from 'src/api/fetch'; import { SCHEDULES } from 'src/constants/api'; import { Schedule, SchedulesList } from 'src/types/schedules'; export const getAllSchedules = () => fetchApi<SchedulesList>(SCHEDULES); export const toggleSchedule = ({ id, isRetired }: Schedule) => fetchApi<Schedule>(SCHEDULES + '/' + id, { method: 'PATCH', headers: { 'Content-type': 'application/json' }, body: JSON.stringify({ isRetired: !isRetired }), });
ericloureiro/schedules-challenge
client/src/utils/isEmpty.ts
<filename>client/src/utils/isEmpty.ts import { Empty, ObjectOfAny } from 'src/types/utils'; const isEmpty = (value: unknown): value is Empty => { if (value == null) { return true; } if (Array.isArray(value) && value.length === 0) { return true; } if (typeof value === 'object' && Object.keys(value as ObjectOfAny).length === 0) { return true; } if (value === '' || value === 0 || value === '0' || value === false) { return true; } return false; }; export default isEmpty;
matthewpwilson/refarch-kc-ui
server/test/ProblemProducer.ts
// A class to send a problem to the bluewaterProblem topic import * as domain from '../routes/fleetDomain'; import AppConfig from '../config/AppConfig'; const kafka = require('kafka-node'); var Producer = kafka.Producer; declare const Buffer; export default class ProblemProducer { config:AppConfig; producer: any; producerReady: boolean = false; constructor() { this.config = new AppConfig(); } public ProblemTopicProducer(p:domain.ProblemReport){ let positionvarAsString = JSON.stringify(p); const buffer = new Buffer.from(positionvarAsString); var kafka = require('kafka-node'), Producer = kafka.Producer, KeyedMessage = kafka.KeyedMessage, client = new kafka.KafkaClient(), producer = new Producer(client), km = new KeyedMessage('key', 'message'), payloads = [ { topic: 'blueProblem', messages: buffer, partition: 0 } ]; producer.on('ready', function () { producer.send(payloads, function (err, data) { console.log("Prodcuer sending the messages"); console.log(data); }); }); producer.on('error', function (err) {}); } public stopProducer(){ this.producer.close(true, () => { console.log("Stop problem producer"); }) } }
khoadaxne15/LastProject
src/redux/actions/userActions.ts
<reponame>khoadaxne15/LastProject import actionCreatorFactory from "typescript-fsa"; import { User } from "../reducers/userReducer"; const factory = actionCreatorFactory("USER"); // insert in profile array export const registerUser = factory<RegisterUserPayload>("REGISTER_USER"); export type RegisterUserPayload = string; export type GetUserPayload = string; export const getUser = factory<GetUserPayload>("GET_USER"); // different from registerUser -- only inserted in admins' users array not in profile array export const addUser = factory<AddUserPayload>("ADD_USER"); export type AddUserPayload = User; export const editUser = factory<EditUserPayload>("EDIT_USER"); export interface EditUserPayload extends Partial<User> { id: string; } export const deleteUser = factory<DeleteUserPayload>("DELETE_USER"); export type DeleteUserPayload = string;
khoadaxne15/LastProject
src/components/product/ProductFeatured.tsx
import React from "react"; import Skeleton, { SkeletonTheme } from "react-loading-skeleton"; import { useHistory } from "react-router-dom"; import { Product } from "../../redux"; import { ImageLoader } from "../common"; export const ProductFeatured: React.FC<ProductFeaturedProps> = ({ product }) => { const history = useHistory(); const onClickItem = () => { if (!product) { return; } history.push(`/product/${product.id}`); }; return ( <SkeletonTheme color="#e1e1e1" highlightColor="#f2f2f2"> <div className="product-display" onClick={onClickItem} role="presentation"> <div className="product-display-img"> {product.image ? ( <ImageLoader alt="" className="product-card-img" src={product.image} /> ) : ( <Skeleton width="100%" height="100%" /> )} </div> <div className="product-display-details"> <h2>{product.name || <Skeleton width={80} />}</h2> <p className="text-subtle text-italic">{product.brand || <Skeleton width={40} />}</p> </div> </div> </SkeletonTheme> ); }; type ProductFeaturedProps = { product: Product; };
khoadaxne15/LastProject
src/redux/actions/filterActions.ts
<filename>src/redux/actions/filterActions.ts<gh_stars>0 import actionCreatorFactory from "typescript-fsa"; import { Filter } from "../reducers"; const factory = actionCreatorFactory("FILTER"); export const setTextFilter = factory<SetTextFilterPayload>("SET_TEXT_FILTER"); export type SetTextFilterPayload = string; export const setBrandFilter = factory<SetBrandFilterPayload>("SET_BRAND_FILTER"); export type SetBrandFilterPayload = string; export const setMinPriceFilter = factory<SetMinPriceFilterPayload>("SET_MIN_PRICE_FILTER"); export type SetMinPriceFilterPayload = number; export const setMaxPriceFilter = factory<SetMaxPriceFilterPayload>("SET_MAX_PRICE_FILTER"); export type SetMaxPriceFilterPayload = number; export const resetFilter = factory<ResetFilterPayload>("RESET_FILTER"); export interface ResetFilterPayload {} export const clearRecentSearch = factory<ClearRecentSearchPayload>("CLEAR_RECENT_SEARCH"); export interface ClearRecentSearchPayload {} export const removeSelectedRecent = factory<RemoveSelectedRecentPayload>("REMOVE_SELECTED_RECENT"); export type RemoveSelectedRecentPayload = string; export const applyFilter = factory<ApplyFilterPayload>("APPLY_FILTER"); export type ApplyFilterPayload = Partial<Filter>;
khoadaxne15/LastProject
src/components/product/ProductGrid.tsx
import React from "react"; import { useBasket } from "../../hooks"; import { Product } from "../../redux"; import { ProductItem } from "./ProductItem"; export const ProductGrid: React.FC<ProductGridProps> = ({ products }) => { const { addToBasket, isItemOnBasket } = useBasket(); return ( <div className="product-grid"> {products.length === 0 ? new Array(12) .fill({}) .map((product, index) => <ProductItem key={`product-skeleton ${index}`} product={product} />) : products.map((product) => ( <ProductItem key={product.id} isItemOnBasket={isItemOnBasket} addToBasket={addToBasket} product={product} /> ))} </div> ); }; type ProductGridProps = { products: Product[]; };
khoadaxne15/LastProject
src/redux/actions/miscActions.ts
import actionCreatorFactory from "typescript-fsa"; const factory = actionCreatorFactory("MISC"); export const setLoading = factory<SetLoadingPayload>("LOADING"); export type SetLoadingPayload = boolean; export const setAuthenticating = factory<SetAuthenticatingPayload>("IS_AUTHENTICATING"); export type SetAuthenticatingPayload = boolean; export const setRequestStatus = factory<SetRequestStatusPayload>("SET_REQUEST_STATUS"); export type SetRequestStatusPayload = { message: string } | undefined; export const setAuthStatus = factory<SetAuthStatusPayload>("SET_AUTH_STATUS"); export type SetAuthStatusPayload = AuthStatus; export type AuthStatus = null | { success: boolean; isError?: boolean; type: string; message: string; };
khoadaxne15/LastProject
src/components/common/Badge.tsx
import React from "react"; export const Badge: React.FC<BadgeProps> = ({ count, children }) => ( <div className="badge"> {children} {count >= 1 && <span className="badge-count">{count}</span>} </div> ); type BadgeProps = { count: number; children: React.ReactNode | React.ReactNode[]; };
khoadaxne15/LastProject
src/constants/routes.ts
export const HOME = "/"; export const SHOP = "/shop"; export const FEATURED_PRODUCTS = "/featured"; export const RECOMMENDED_PRODUCTS = "/recommended"; export const ACCOUNT = "/account"; export const ACCOUNT_EDIT = "/account/edit"; export const ADMIN_DASHBOARD = "/admin/dashboard"; export const ADMIN_PRODUCTS = "/admin/products"; export const ADMIN_USERS = "/admin/users"; export const ADD_PRODUCT = "/admin/add"; export const EDIT_PRODUCT = "/admin/edit"; export const SEARCH = "/search/:searchKey"; export const SIGNIN = "/signin"; export const SIGNOUT = "/signout"; export const SIGNUP = "/signup"; export const FORGOT_PASSWORD = <PASSWORD>"; export const CHECKOUT_STEP_1 = "/checkout/step1"; export const CHECKOUT_STEP_2 = "/checkout/step2"; export const CHECKOUT_STEP_3 = "/checkout/step3"; export const VIEW_PRODUCT = "/product/:id";
khoadaxne15/LastProject
src/routers/ClientRoute.tsx
import React from "react"; import { connect } from "react-redux"; import { Redirect, Route } from "react-router-dom"; import { ADMIN_DASHBOARD, SIGNIN } from "../constants"; import { AppState } from "../redux"; const _ClientRoute: React.FC<ClientRouteProps> = ({ isAuth, role, component: Component, ...rest }) => ( <Route {...rest} component={(props: JSX.IntrinsicAttributes) => { if (isAuth && role === "USER") { return ( <main className="content"> <Component {...props} /> </main> ); } if (isAuth && role === "ADMIN") { return <Redirect to={ADMIN_DASHBOARD} />; } return ( <Redirect to={{ pathname: SIGNIN, state: { from: (props as any).location }, }} /> ); }} /> ); _ClientRoute.defaultProps = { isAuth: false, role: "USER", exact: false, }; type ClientRouteProps = { isAuth?: boolean; role?: string; location?: any; component: any; exact?: boolean; path: string; }; const mapStateToProps = (params: AppState) => ({ isAuth: !!params.auth, role: params.auth?.role || "", }); export const ClientRoute = connect(mapStateToProps)(_ClientRoute);
khoadaxne15/LastProject
src/views/account/components/index.ts
<reponame>khoadaxne15/LastProject<filename>src/views/account/components/index.ts export * from "./UserAccountTab"; export * from "./UserAvatar"; export * from "./UserOrdersTab"; export * from "./UserTab"; export * from "./UserWishListTab";
khoadaxne15/LastProject
src/components/common/SearchBar.tsx
import { SearchOutlined } from "@ant-design/icons"; import React, { useRef, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useHistory } from "react-router-dom"; import { AppState, clearRecentSearch, FilterState, removeSelectedRecent } from "../../redux"; export const SearchBar = () => { const [searchInput, setSearchInput] = useState(""); const { filter, isLoading } = useSelector<AppState, { filter: FilterState; isLoading: boolean }>((state) => ({ filter: state.filter, isLoading: state.app.loading, })); const searchbarRef = useRef<HTMLDivElement | null>(null); const history = useHistory(); const dispatch = useDispatch(); const isMobile = window.screen.width <= 800; const onSearchChange = (e: any) => { const val = e.target.value.trimStart(); setSearchInput(val); }; const onKeyUp = (e: any) => { if (e.keyCode === 13) { // @ts-ignore e.target.blur(); searchbarRef.current?.classList.remove("is-open-recent-search"); if (isMobile) { history.push("/"); } history.push(`/search/${searchInput.trim().toLowerCase()}`); } }; const recentSearchClickHandler = (e: any) => { const searchBar = e.target.closest(".searchbar"); if (!searchBar.current) { searchbarRef.current?.classList.remove("is-open-recent-search"); document.removeEventListener("click", recentSearchClickHandler); } }; const onFocusInput = (e: any) => { e.target.select(); if (filter.recent?.length !== 0) { searchbarRef.current?.classList.add("is-open-recent-search"); document.addEventListener("click", recentSearchClickHandler); } }; const onClickRecentSearch = (keyword: string) => { searchbarRef.current?.classList.remove("is-open-recent-search"); history.push(`/search/${keyword.trim().toLowerCase()}`); }; const onClearRecent = () => { dispatch(clearRecentSearch({})); }; return ( <> <div className="searchbar" ref={searchbarRef}> <SearchOutlined className="searchbar-icon" /> <input className="search-input searchbar-input" onChange={onSearchChange} onKeyUp={onKeyUp} onFocus={onFocusInput} placeholder="Search product..." readOnly={isLoading} type="text" value={searchInput} /> {filter.recent?.length !== 0 && ( <div className="searchbar-recent"> <div className="searchbar-recent-header"> <h5>Recent Search</h5> <h5 className="searchbar-recent-clear text-subtle" onClick={onClearRecent} role="presentation"> Clear </h5> </div> {filter.recent?.map((item, index) => ( <div className="searchbar-recent-wrapper" key={`search-${item}-${index}`}> <h5 className="searchbar-recent-keyword margin-0" onClick={() => onClickRecentSearch(item)} role="presentation"> {item} </h5> <span className="searchbar-recent-button text-subtle" onClick={() => dispatch(removeSelectedRecent(item))} role="presentation"> X </span> </div> ))} </div> )} </div> </> ); };
khoadaxne15/LastProject
src/views/auth/signin/index.tsx
<reponame>khoadaxne15/LastProject import { ArrowRightOutlined, LoadingOutlined } from "@ant-design/icons"; import { Field, Form, Formik } from "formik"; import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { Link } from "react-router-dom"; import * as Yup from "yup"; import { SocialLogin } from "../../../components/common"; import { CustomInput } from "../../../components/formik"; import { FORGOT_PASSWORD, SIGNUP } from "../../../constants"; import { useDocumentTitle, useScrollTop } from "../../../hooks"; import { signIn, setAuthenticating, setAuthStatus, AppState, AuthStatus, MiscState } from "../../../redux"; const SignInSchema = Yup.object().shape({ email: Yup.string().email("Email is not valid.").required("Email is required."), password: Yup.string().required("Password is required."), }); export const SignIn: React.FC<SignInProps> = ({ history }) => { const { authStatus, isAuthenticating } = useSelector< AppState, { authStatus: AuthStatus; isAuthenticating: MiscState["isAuthenticating"] } >((state) => ({ authStatus: state.app.authStatus, isAuthenticating: state.app.isAuthenticating, })); const dispatch = useDispatch(); useScrollTop(); useDocumentTitle("Sign In | TK"); useEffect( () => () => { dispatch(setAuthStatus(null)); dispatch(setAuthenticating(false)); }, [dispatch] ); const onSignUp = () => history.push(SIGNUP); const onSubmitForm = (form: { email: string; password: string }) => { dispatch(signIn.started(form)); }; const onClickLink = (e: any) => { if (isAuthenticating) { e.preventDefault(); } }; return ( <div className="auth-content"> {authStatus?.success && ( <div className="loader"> <h3 className="toast-success auth-success"> {authStatus.message} <LoadingOutlined /> </h3> </div> )} {!authStatus?.success && ( <> {authStatus?.message && <h5 className="text-center toast-error">{authStatus?.message}</h5>} <div className={`auth ${authStatus?.message && !authStatus?.success && "input-error"}`}> <div className="auth-main"> <h3>Sign in to TK</h3> <br /> <div className="auth-wrapper"> <Formik initialValues={{ email: "", password: "", }} validateOnChange validationSchema={SignInSchema} onSubmit={onSubmitForm}> {() => ( <Form> <div className="auth-field"> <Field disabled={isAuthenticating} name="email" type="email" label="Email" placeholder="<EMAIL>" component={CustomInput} /> </div> <div className="auth-field"> <Field disabled={isAuthenticating} name="password" type="password" label="Password" placeholder="<PASSWORD>" component={CustomInput} /> </div> <br /> <div className="auth-field auth-action"> <Link onClick={onClickLink} style={{ textDecoration: "underline" }} to={FORGOT_PASSWORD}> <span>Forgot password?</span> </Link> <button className="button auth-button" disabled={isAuthenticating} type="submit"> {isAuthenticating ? "Signing In" : "Sign In"} &nbsp; {isAuthenticating ? <LoadingOutlined /> : <ArrowRightOutlined />} </button> </div> </Form> )} </Formik> </div> </div> <div className="auth-divider"> <h6>OR</h6> </div> <SocialLogin isLoading={isAuthenticating} /> </div> <div className="auth-message"> <span className="auth-info"> <strong>Don&apos;t have an account?</strong> </span> <button className="button button-small button-border button-border-gray button-icon" disabled={isAuthenticating} onClick={onSignUp} type="button"> Sign Up </button> </div> </> )} </div> ); }; type SignInProps = { history: { push: (path: string) => void; }; };
khoadaxne15/LastProject
src/components/basket/BasketItem.tsx
import { CloseOutlined } from "@ant-design/icons"; import React from "react"; import { useDispatch } from "react-redux"; import { Link } from "react-router-dom"; import { displayMoney } from "../../helpers"; import { Product, removeFromBasket } from "../../redux"; import { ImageLoader } from "../common"; import { BasketItemControl } from "./BasketItemControl"; interface BasketItemProps { product: Product; basket: Product[]; } export const BasketItem: React.FC<BasketItemProps> = ({ product }) => { const dispatch = useDispatch(); const onRemoveFromBasket = () => dispatch(removeFromBasket(product.id)); return ( <div className="basket-item"> <BasketItemControl product={product} /> <div className="basket-item-wrapper"> <div className="basket-item-img-wrapper"> <ImageLoader alt={product.name} className="basket-item-img" src={product.image || ""} /> </div> <div className="basket-item-details"> <Link to={`/product/${product.id}`} onClick={() => document.body.classList.remove("is-basket-open")}> <h4 className="underline basket-item-name">{product.name}</h4> </Link> <div className="basket-item-specs"> <div> <span className="spec-title">Quantity</span> <h5 className="my-0">{product.quantity}</h5> </div> <div> <span className="spec-title">Size</span> <h5 className="my-0">{product.selectedSize} mm</h5> </div> <div> <span className="spec-title">Color</span> <div style={{ backgroundColor: product.selectedColor || product.availableColors[0], width: "15px", height: "15px", borderRadius: "50%", }} /> </div> </div> </div> <div className="basket-item-price"> <h4 className="my-0">{displayMoney(product.price * product.quantity)}</h4> </div> <button className="basket-item-remove button button-border button-border-gray button-small" onClick={onRemoveFromBasket} type="button"> <CloseOutlined /> </button> </div> </div> ); };
khoadaxne15/LastProject
src/redux/reducers/authReducer.ts
<filename>src/redux/reducers/authReducer.ts import { AnyAction } from "typescript-fsa"; import { signIn, signOut } from "../actions"; export type AuthState = { id: string; role: string; provider?: string; } | null; export function authReducer(state: AuthState | undefined, action: AnyAction): AuthState { if (state === undefined) { return null; } if (signIn.done.match(action)) { return { ...action.payload.result, }; } if (signOut.done.match(action)) { return null; } return state; }
khoadaxne15/LastProject
src/components/common/PriceRange/Tick.tsx
import React from "react"; export const Tick: React.FC<TickProps> = ({ tick, count, format }) => ( <div> <div style={{ position: "absolute", marginTop: 17, width: 1, height: 5, backgroundColor: "rgb(200,200,200)", left: `${tick.percent}%`, }} /> <div style={{ position: "absolute", marginTop: 25, fontSize: 10, textAlign: "center", marginLeft: `${-(100 / count) / 2}%`, width: `${100 / count}%`, left: `${tick.percent}%`, }}> {format?.(tick.value)} </div> </div> ); type TickProps = { tick: { id: string; value: number; percent: number; }; count: number; format?: (value: number) => React.ReactNode; }; Tick.defaultProps = { format: (d) => d, };
khoadaxne15/LastProject
src/App.tsx
import React, { StrictMode } from "react"; import { Provider } from "react-redux"; import { Store } from "redux"; import { Persistor } from "redux-persist"; import { PersistGate } from "redux-persist/integration/react"; import { Preloader } from "./components"; import { AppState } from "./redux"; import { AppRouter } from "./routers/AppRouter"; export const App: React.FC<AppProps> = ({ store, persistor }) => ( <StrictMode> <Provider store={store}> <PersistGate loading={<Preloader />} persistor={persistor}> <AppRouter /> </PersistGate> </Provider> </StrictMode> ); type AppProps = { store: Store<AppState>; persistor: Persistor; };
khoadaxne15/LastProject
src/hooks/index.ts
<filename>src/hooks/index.ts export * from "./useBasket"; export * from "./useDidMount"; export * from "./useDocumentTitle"; export * from "./useFeaturedProducts"; export * from "./useFileHandler"; export * from "./useModal"; export * from "./useProduct"; export * from "./useRecommendedProducts"; export * from "./useScrollTop";